Next / Previous / Contents / Shipman's homepage

5.10. FollowedBy: Adding lookahead constraints


This class is used to specify a lookahead; that is, some content which must appear in the input, but you don't want to match any of it. Here is an example.

>>> name = pp.Word(pp.alphas)
>>> oneOrTwo = pp.Word('12', exact=1)
>>> number = pp.Word(pp.nums)
>>> pat = name + pp.FollowedBy(oneOrTwo) + number
>>> print pat.parseString('Robin144')
['Robin', '144']
>>> print pat.parseString('Robin88')
pyparsing.ParseException: Expected W:(12) (at char 5), (line:1, col:6)

The name pattern matches one or more letters; the oneOrTwo pattern matches either '1' or '2'; and the number pattern matches one or more digits. The expression “pp.FollowedBy(oneOrTwo)” requires that the next thing after the name matches the oneOrTwo pattern, but the input is not advanced past it.

Thus, the number pattern matches one or more digits, including the '1' or '2' just after the name. In the 'Robin88' example, the match fails because the character just after 'Robin' is neither '1' or '2'.