Re: [Pyparsing] How to distinguish a variable from a integer
Brought to you by:
ptmcg
From: Paul M. <pt...@au...> - 2009-05-14 17:57:16
|
> -----Original Message----- > From: spir [mailto:den...@fr...] > You could also add a lookahead for !(letter | '_') trailing after the > definition of number, but then your definition of variable is unclear. It > should be required that a variable has at least one non-digit char. Which > is uneasy ;-) > Yes, Denis has another approach. You can use parse actions as a way to add validation logic like Denis suggests. Here is a validating parse action that you could attach to variable to ensure that it contains at least one non-digit. def mustHaveAtLeastOneNonDigit(tokens): if all(c.isdigit() for c in tokens[0]): raise ParseException("variable must have at least one non-digit") variable.setParseAction(mustHaveAtLeastOneNonDigit) Parse actions can serve a number of uses. They can also be chained so that multiple actions or validations can be invoked: ip_part = Word(nums) convertToInt = lambda tokens: int(tokens[0]) def validateRange(tokens): if not 0 <= tokens[0] < 256: raise ParseException("value must be in range 0-255") ip_part.setParseAction(convertToInt, validateRange) # or: # ip_part.setParseAction(convertToInt) # ip_part.addParseAction(validateRange) ip_addr = Combine(ip_part + ('.'+ip_part)*3 ) print ip_addr.parseString("192.168.0.255") print ip_addr.parseString("123.456.789.000") -- Paul |