2013-02-11 48 views
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 " 
+1

您可以返回函數而不是使用'lambda',例如'return regexobj.match' – jfs 2013-02-11 19:42:55

+2

'g = lambda x:f(x)'在這種情況下是冗餘冗餘的。你可以用'g = f'來代替。 – jfs 2013-02-11 20:14:34

+0

確實thx!將改變它.. – Hugo 2013-02-11 20:29:02

回答

5

您可以使用逆向引用和負前瞻。

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

反向引用被替換爲任何第一組中的被匹配:(\d)

負先行防止匹配如果從以下字符匹配表達式成功。

所以這基本上說匹配一個數字(我們稱之爲「N」)。如果下一個字符是N,則匹配失敗。如果不是,則再匹配一個數字。

+0

哦,人!非常感謝 !!! – Hugo 2013-02-11 19:48:16