Next / Previous / Contents / Shipman's homepage

5.23. Or: Parse one of a set of alternatives

pp.Or(parserList)

An instance of this class matches one of a given set of parsers; the argument is a sequence containing those parsers. If more than one of the parsers match, the parser used will be the one that matches the longest string of text.

>>> name = pp.Word(pp.alphas)
>>> number = pp.Word(pp.nums)
>>> nameNoOrBang = pp.Or([name, number, pp.Literal('!')])
>>> print nameNoOrBang.parseString('Brian')
['Brian']
>>> print nameNoOrBang.parseString('73')
['73']
>>> print nameNoOrBang.parseString('!')
['!']
>>> several = pp.OneOrMore(nameNoOrBang)
>>> print several.parseString('18 years of total silence!')
['18', 'years', 'of', 'total', 'silence', '!']

You may also use the “^” operator to construct a set of alternatives. This line is equivalent to the third line of the example above:

>>> nameNoOrBang = name ^ number ^ pp.Literal('!')