如何在pyparsing中禁止文字之间的空格?

时间:2011-04-24 04:08:29

标签: python pyparsing

grammar = Literal("from") + Literal(":") + Word(alphas)

语法需要拒绝from : mary并且只接受from:mary,即没有任何交错空格。如何在pyparsing中强制执行此操作?感谢

1 个答案:

答案 0 :(得分:4)

您可以使用Combine吗?

grammar = Combine(Literal("from") + Literal(":") + Word(alphas))

那么:

编辑以回应您的评论。

真的?

>>> grammar = pyparsing.Combine(Literal("from") + Literal(":") + Word(pyparsing.alphas))
>>> grammar.parseString('from : mary')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/pymodules/python2.6/pyparsing.py", line 1076, in parseString
    raise exc
pyparsing.ParseException: Expected ":" (at char 4), (line:1, col:5)
>>> grammar.parseString('from:mary')
(['from:mary'], {})