I’m trying to write a parser with pyparsing. Here’s a snippit from my grammar definitions:
import pyparsing as pp
Modifier = pp.Word(pp.alphas)
Name = pp.Literal("foobar")
Sentence = pp.Optional(Modifier) + Name + pp.Group(pp.OneOrMore(Modifier))
And here’s what happens when I parse a sample string:
>>> print Sentence.parseString("testA FOOBAR testB testC")
['testA', 'FOOBAR', ['testB', 'testC']]
Is there any way to modify my grammar rules above so it pushes the first optional modifier into the following group?
Example:
>>> print MagicSentence.parseString("test A FOOBAR testB testC")
['FOOBAR', ['testA', 'testB', 'testC']]
The most straightforward way to do this is to parse it pretty much as you have done, but add a parse action to Sentence to do the element re-arranging. Something like this: