3

我想使用pypeg$f匹配表单的类型, $c, ... ,所以我尝试将其放入如下:$dEnum

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

但是,这失败了:

>>> 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

我也试过用替换$x\$x转义这个$角色。我还尝试预先添加r"\$x",希望它将其视为正则表达式对象。这些组合似乎都不起作用并给出相同的错误消息。我如何让它与我给出的例子相匹配?

4

1 回答 1

2

关键字的默认正则表达式\w+. 您可以通过设置Keyword.regex类变量来更改它:

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)
于 2017-03-22T16:29:23.503 回答