Friday, 15 January 2010

python - Looking for the right RE -



python - Looking for the right RE -

just started regular expressions... im looking regular expression \b\d\d\b digits may not same.(e.g 23 should match 22 should not) i,ve tried lot ( involving backreferences ) failed. i've tried re's code below ( python 2.7.3) nil matched far

import re # take raw string(e) input # , homecoming function argument # 'string' returns re.match object # on succes. else returns none def mymatch(e): regexobj= re.compile(e) homecoming regexobj.match menu= raw_input expr= "expression\n:>" quit= 'q' newexpression= 'r' str2match= "string match\n:>" validate= mymatch(menu(expr)) # exits when user # hits 'q' while true: # set string match or nail 'q' or 'r' alternative = menu(str2match) if option== quit: break #invokes when user hits 'r' #setting new look elif option== newexpression: validate= mymatch(menu(expr)) go on rematchobject= validate(option) # have match ! if rematchobject: print "pattern: ",rematchobject.re.pattern print "group(0): ",rematchobject.group() print "groups: ",rematchobject.groups() else: print "no match found "

you can utilize backreferencing , negative lookahead.

\b(\d)(?!\1)\d\b

the backreference replaced whatever matched in first group: (\d)

a negative lookahead prevents match succeeding if next characters match expression.

so says match number (we'll phone call "n"). if next character n, fail match. if not, match 1 more number.

python regex

No comments:

Post a Comment