Search code examples
pyparsing

How to define numbers in PyParsing?


I need to define a rule for integer numbers in PyParsing, something like:

import pyparsing
plusorminus = pyparsing.Literal('+') | pyparsing.Literal('-')
number = pyparsing.Word(pyparsing.nums) 
hexdecimal = pyparsing.Word(pyparsing.hexnums)
decimal = pyparsing.Combine(pyparsing.Optional(plusorminus) + number)
integer = pyparsing.Combine(pyparsing.Optional(plusorminus) + ((pyparsing.CaselessLiteral('0x') + hexdecimal) |number)).addParseAction(lambda toks: int(toks[0], 0))

The problem is with the trailings (non digits), for e.g. numbers and letter:

integer.parseString('123a').pprint()

doesn't return an error ?


Solution

  • When calling parsestring, give it the parameter parseAll=True. Thus

    integer.parseString('123a', parseAll=True).pprint()
    

    throws an exception.

    From the pyparsing documentation: If you want the grammar to require that the entire input string be successfully parsed, then set parseAll to True.