Re: [Pyparsing] How to distinguish a variable from a integer
Brought to you by:
ptmcg
From: Gustavo N. <me...@gu...> - 2009-05-14 23:02:32
|
Yes, it worked that way! Thank you very much once again, Denis and Paul! :) - Gustavo. Paul said: > 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") -- Gustavo Narea <xri://=Gustavo>. | Tech blog: =Gustavo/(+blog)/tech ~ About me: =Gustavo/about | |