Using a dollar sign in enum (pypeg)?

163 views Asked by At

I want to match types of the form either $f, $c, ..., $d using pypeg, so I tried putting it in an Enum as follows:

class StatementType(Keyword):
    grammar = Enum( K("$f"), K("$c"), 
                    K("$v"), K("$e"),
                    K("$a"), K("$p"),
                    K("$d"))

However, this fails:

>>> k = parse("$d", StatementType)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.6/site-packages/pypeg2/__init__.py", line 667, in parse
    t, r = parser.parse(text, thing)
  File "/usr/local/lib/python3.6/site-packages/pypeg2/__init__.py", line 794, in parse
    raise r
  File "<string>", line 1
    $d
    ^
SyntaxError: expecting StatementType

I have also tried replacing the $x with \$x to escape the $ character. I also tried prepending r"\$x" in hopes that it treats it as a regex object. Neither of these combinations seem to work and give the same error message. How do I get it to match the example I gave?

1

There are 1 answers

0
ThisSuitIsBlackNot On BEST ANSWER

The default regex for Keywords is \w+. You can change it by setting the Keyword.regex class variable:

class StatementType(Keyword):
    grammar = Enum( K("$f"), K("$c"),
                    K("$v"), K("$e"),
                    K("$a"), K("$p"),
                    K("$d"))

Keyword.regex = re.compile(r"\$\w") # e.g. $a, $2, $_
k = parse("$d", StatementType)