Next / Previous / Contents / Shipman's homepage

5.18. MatchFirst: Try multiple matches in a given order

pp.MatchFirst(parserList)

Use an instance of this class when you want to try to match two or more different parser, but you want to specify the order of the tests. The parserList argument is a list of parsers.

A typical place to use this is to match the text against a set of strings in which some strings are substrings of others. For example, suppose your input text has two different command names CATCH and CAT: you should test for CATCH first. If you test for CAT first, it will match the first three characters of CATCH, which is probably not what you want.

>>> name = pp.Word(pp.alphas)
>>> keySet = pp.MatchFirst([pp.Literal('CATCH'), pp.Literal('CAT')])
>>> keyName = keySet + name
>>> print keyName.parseString('CATCH bullatfour', parseAll=True)
['CATCH', 'bullatfour']
>>> print keyName.parseString('CAT gotchertung')
['CAT', 'gotchertung']

You may also get the effect of this class by combining the component parsers with the “|” operator. The definition of keySet in the above example could also have been done this way:

>>> keySet = pp.Literal('CATCH') | pp.Literal('CAT')