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

The grammar needs to reject from : mary and only accept from:mary i.e. without any interleaving spaces. How can I enforce this in pyparsing ? Thanks

Frankie Ribery
  • 11,933
  • 14
  • 50
  • 64

1 Answers1

7

Can you use Combine?

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

So then:

EDIT in response to your comment.

Really?

>>> 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'], {})
sjr
  • 9,769
  • 1
  • 25
  • 36
  • `Combine` does not throw a `ParseException` for `from : mary`. I want the error to be thrown. – Frankie Ribery Apr 24 '11 at 05:21
  • 3
    Also, read up on the `leaveWhitespace` method to suppress whitespace-skipping for specific expressions. Call this method on any expression that must match without skipping spaces, in your case the ':' and the word containing the name. – PaulMcG Apr 24 '11 at 14:44