简体   繁体   English

Re.match() 总是返回 none

[英]Re.match() returns always none

I feel kind of stupid but it does not work:我觉得有点愚蠢,但它不起作用:

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'

I have the ur' if the user given a is unicode.我有ur' ,如果用户给定a是unicode。 I want to print success if wekjb or ABB is in the string but I always get None as the result of the match .如果wekjbABB在字符串中,我想打印成功,但我总是得到None作为match的结果。

re.match is implicitly anchored to the start of the string. re.match隐式锚定到字符串的开头。 If you want to search a string for a substring that can be anywhere within it, then you need to use re.search :如果要在字符串中搜索可以位于其中任何位置的子字符串,则需要使用re.search

import re

a = " ebrj wjrbw erjwek wekjb rjERJK ABB RAEJKE BWE RWEJBEWJ B KREWBJ BWERBJ32J3B23B J BJ235JK BJJ523 2"

print re.search(ur'(wekjb|ABB)',a).group()
if re.search(ur'(wekjb|ABB)',a):
    print 'success'

Output:输出:

wekjb
success

Also, Python Regexes do not need to have a / at the start and end.此外,Python 正则表达式不需要在开头和结尾有/

Lastly, I added .group() to the end of the print line because I think this is what you want.最后,我将.group()添加到print行的末尾,因为我认为这就是您想要的。 Otherwise, you'd get something like <_sre.SRE_Match object at 0x01812220> , which isn't too useful.否则,你会得到类似<_sre.SRE_Match object at 0x01812220> ,这不是很有用。

It's because of that match method returns None if it couldn't find expected pattern, if it find the pattern it would return an object with type of _sre.SRE_match .这是因为match方法如果找不到预期的模式则返回None ,如果找到该模式,它将返回一个类型为_sre.SRE_match的对象。

So, if you want Boolean ( True or False ) result from match you must check the result is None or not!因此,如果您想要match布尔值( TrueFalse )结果,您必须检查结果是否为None

You could examine texts is matched or not somehow like this:您可以像这样检查文本是否匹配:

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!")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM