1
剛開始使用正則表達式...我正在尋找一個正則表達式
類似於\ b \ d \ d \ b,但數字 可能不一樣(例如23應匹配
但22不應該)我試了很多 (涉及反向引用),但他們都 失敗。
我試圖重新與下面 (蟒蛇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 "
您可以返回函數而不是使用'lambda',例如'return regexobj.match' – jfs 2013-02-11 19:42:55
'g = lambda x:f(x)'在這種情況下是冗餘冗餘的。你可以用'g = f'來代替。 – jfs 2013-02-11 20:14:34
確實thx!將改變它.. – Hugo 2013-02-11 20:29:02