Next / Previous / Contents / Shipman's homepage

6.10. matchPreviousExpr(): Match the text that the preceding expression matched


This function returns a new parser that matches not only the same pattern as the given parser, but it matches the value that was matched by parser.

>>> name = pp.Word(pp.alphas)
>>> name2 = pp.matchPreviousExpr(name)
>>> dash2 = name + pp.Literal('-') + name2
>>> print dash2.parseString('aye-aye')
['aye', '-', 'aye']
>>> print dash2.parseString('aye-nay')
pyparsing.ParseException:  (at char 0), (line:1, col:1)
>>> print dash2.parseString('no-now')
pyparsing.ParseException:  (at char 0), (line:1, col:1)

The last example above failed because, even though the string "no" occurred both before and after the hyphen, the name2 parser matched the entire string "now" before it tested to see if it matched the previous occurrence "no". Compare the behavior of Section 6.11, “matchPreviousLiteral(): Match the literal text that the preceding expression matched”.