Python Re.match()始终返回none
我觉得有点傻,但这不管用:Python Re.match()始终返回none,python,regex,Python,Regex,我觉得有点傻,但这不管用: import re a = " ebrj wjrbw erjwek wekjb rjERJK ABB RAEJKE BWE RWEJBEWJ B KREWBJ BWERBJ32J3B23B J BJ235JK BJJ523 2" print re.match(ur'/(wekjb|ABB)/',a) if re.match(ur'/(wekjb|ABB)/',a): print 'success' 如果用户给定的a是unicode,则我有ur'。如果we
import re
a = " ebrj wjrbw erjwek wekjb rjERJK ABB RAEJKE BWE RWEJBEWJ B KREWBJ BWERBJ32J3B23B J BJ235JK BJJ523 2"
print re.match(ur'/(wekjb|ABB)/',a)
if re.match(ur'/(wekjb|ABB)/',a):
print 'success'
如果用户给定的a
是unicode,则我有ur'
。如果wekjb
或ABB
在字符串中,但由于match
隐式地锚定到字符串的开头,我总是得到None
,那么我想打印success。如果要在字符串中的任意位置搜索子字符串,则需要使用:
输出:
wekjb
success
此外,Python正则表达式不需要在开始和结束处有/
最后,我在
打印
行的末尾添加了.group()
,因为我认为这是您想要的。否则,您会得到类似于
,这不是很有用。这是因为match
方法返回None
,如果它找不到预期的模式,如果它找到模式,它将返回类型为\sre.sre\u match
的对象
因此,如果您想要布尔(True
或False
)结果来自match
,则必须检查结果是否为None
你可以这样检查文本是否匹配:
string_to_evaluate = "Your text that needs to be examined"
expected_pattern = "pattern"
if re.match(expected_pattern, string_to_evaluate) is not None:
print("The text is as you expected!")
else:
print("The text is not as you expected!")
尝试使用
.search()
而不是.match()
.match()
被锚定到字符串的开头。在a
中没有/
的实例-为什么在您的regexp中有/
的实例?我不认为是“re.match
查找精确匹配”的情况。而是match()
隐式地锚定在行的开头。但也许我只是在那里划船。。?表达式ur.*(wekjb | ABB)
很好用。@TravisGriggs-不,很好。最好是技术性的。我调整了我的帖子并添加了一个链接供进一步参考。
string_to_evaluate = "Your text that needs to be examined"
expected_pattern = "pattern"
if re.match(expected_pattern, string_to_evaluate) is not None:
print("The text is as you expected!")
else:
print("The text is not as you expected!")