Reputation: 109
Just started with regular expressions... Im looking for a regular expression
something like \b\d\d\b but the digits
may not be the same.(e.g 23 should match
but 22 should not) I,ve tried a lot
( involving backreferences ) but they all
failed.
I've tried RE's with the code below
( python 2.7.3) but nothing matched so far
import re
# accept a raw string(e) as input
# and return a function with an argument
# 'string' which returns a re.Match object
# on succes. Else it returns None
def myMatch(e):
RegexObj= re.compile(e)
return RegexObj.match
menu= raw_input
expr= "expression\n:>"
Quit= 'q'
NewExpression= 'r'
str2match= "string to match\n:>"
validate= myMatch(menu(expr))
# exits when the user # hits 'q'
while True:
# set the string to match or hit 'q' or 'r'
option = menu(str2match)
if option== Quit: break
#invokes when the user hits 'r'
#setting the new expression
elif option== NewExpression:
validate= myMatch(menu(expr))
continue
reMatchObject= validate(option)
# we have a match !
if reMatchObject:
print "Pattern: ",reMatchObject.re.pattern
print "group(0): ",reMatchObject.group()
print "groups: ",reMatchObject.groups()
else:
print "No match found "
Upvotes: 1
Views: 105
Reputation: 25810
You can use backreferencing and a negative lookahead.
\b(\d)(?!\1)\d\b
The backreference is replaced with whatever was matched in the first group: (\d)
A negative lookahead prevents the match from succeeding if the following characters match the expression.
So this basically says match a number (we'll call it "N"). If the next character is N, fail the match. If not, match one more number.
Upvotes: 5