Next / Previous / Contents / Shipman's homepage

5.22. Optional: Match an optional pattern

pp.Optional(parser, default=D)

Use this pattern when a syntactic element is optional. The parser argument is a parser for the optional pattern. By default, if the pattern is not present, no content is added to the ParseResult; if you would like to supply content to be added in that case, provide it as the default keyword option.

>>> letter = pp.Word(pp.alphas, exact=1)
>>> number = pp.Word(pp.nums)
>>> chapterNo = number + pp.Optional(letter)
>>> print chapterNo.parseString('23')
>>> print chapterNo.parseString('23c')
['23', 'c']
>>> chapterX = number + pp.Optional(letter, default='*')
>>> print chapterX.parseString('23')
['23', '*']