Next / Previous / Contents / Shipman's homepage

5.6. Combine: Fuse components together

pp.Combine(parser, joinString='', adjacent=True)

The purpose of this class is to modify a parser containing several pieces so that the matching string will be returned as a single item in the returned ParseResults instance. The return value is another ParserElement instance that matches the same syntax as parser, but combines the pieces in the result.


A parser, as a ParserElement instance.


A string that will be inserted between the pieces of the matched text when they are concatenated in the result.


In the default case, adjacent=True, the text matched by components of the parser must be adjacent. If you pass adjacent=False, the result will match text containing the components of parser even if they are separated by other text.

>>> hiwayPieces = pp.Word(pp.alphas) + pp.Word(pp.nums)
>>> print hiwayPieces.parseString('I25')
['I', '25']
>>> hiway = pp.Combine(hiwayPieces)
>>> print hiway.parseString('I25')
>>> print hiway.parseString('US380')

In the example above, hiwayPieces matches one or more letters (pp.Word(pp.alphas)) followed by one or more digits (pp.Word(pp.nums)). Because it has two components, a match on hiwayPieces will always return a list of two strings. The hiway parser returns a list containing one string, the concatenation of the matched pieces.

>>> myway = pp.Combine(hiwayPieces, joinString='*', adjacent=False)
>>> print myway.parseString('I25')
>>> print myway.parseString('Interstate 25')
>>> print hiway.parseString('Interstate 25')
pyparsing.ParseException: Expected W:(0123...) (at char 10), (line:1,