刚开始使用正则表达式...我正在寻找一个正则表达式
类似于\b\d\d\b,但数字可能不同。(例如,23应匹配
但22不应该)我已经尝试了很多(涉及反向引用),但它们都失败了。
我已经用下面的代码( python 2.7.3)尝试了RE,但到目前为止还没有匹配到的代码
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 "发布于 2013-02-12 03:37:02
您可以使用反向引用和负向前视。
\b(\d)(?!\1)\d\b反向引用被替换为第一个组中匹配的任何内容:(\d)
如果以下字符与表达式匹配,则否定的先行查找会阻止匹配成功。
所以这基本上是说匹配一个数字(我们称之为"N")。如果下一个字符是N,则匹配失败。如果不匹配,则再匹配一个数字。
https://stackoverflow.com/questions/14819514
复制相似问题