Type of results verification with pyparsing


I'm new using pyparsing, but I can't find how to solve this quite easy issue. I have (for the moment) a simple grammar, but I can' t find the way to discriminate the result of parsing according the types I defined in my grammar.

Maybe it' d be easier to explain it with an example. Supposing this element:

elem = foo | bar

When I invoke:


supposing the string matches with my grammar, how can I discriminate if it matches with ' foo' or with ' bar'? I get an instance object of ParseResults with no such metadata.

Thanks in advance.

You could assign a name to them (a convoluted example using Literal):

foo = Literal('foo').setResultsName('foo')
bar = Literal('bar').setResultsName('bar')
grammar = foo | bar
parsed = grammar.parseString('bar foo')
print parsed
# (['bar'], {'bar': [('bar', 0)]})
print parsed.asDict()
# {'bar': 'bar'}