Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a dollar sign in enum (pypeg)?

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?

like image 530
Dair Avatar asked Dec 12 '25 02:12

Dair


1 Answers

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)
like image 180
ThisSuitIsBlackNot Avatar answered Dec 13 '25 15:12

ThisSuitIsBlackNot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!