2017-07-18 72 views
0

不知道为什么这不匹配,无法正常工作?看来事情是错的正则表达式这样的,虽然我在网上正则表达式测试仪Python正则表达式分析变量

current_name = "bob[0]" 
regex_match = re.compile('%s'%current_name) 
if re.match(regex_match, current_name): 
    print "matched" 
+1

你想从该字符串匹配什么? '['和']'之间的值? – CoryKramer

+2

你试图将字符串'bob [0]'与模式'bob [0] \ [[。*]]'匹配到? – janos

+0

如果你想将反斜杠放入正则表达式中而不必将它们加倍,可以将它设为原始字符串 - “r'whatever”。事实上,你的反斜杠正在迷失,因为下面的字符不是反斜杠转义的一部分。 – jasonharper

回答

0
current_name = "bob[0]" 
regex_match = re.compile('%s'%current_name.replace('[', r'\[')) 
if re.match(regex_match, current_name): 
    print "matched" 

这左方括号是导致问题出现,测试了它,它甚至不匹配。这将打印“匹配”