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'
如果用户给定的 a
是 unicode,我就有 ur'
.如果 wekjb
或 ABB
在字符串中,我想打印成功,但我总是得到 None
作为 match的结果代码>.
I have the ur'
if the user given a
is 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
.
推荐答案
re.match
隐式锚定到字符串的开头.如果要在字符串中搜索可以位于其中任何位置的子字符串,则需要使用 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'
输出:
wekjb
success
此外,Python 正则表达式的开头和结尾不需要 /
.
Also, Python Regexes do not need to have a /
at the start and end.
最后,我将 .group()
添加到 print
行的末尾,因为我认为这就是您想要的.否则,您会得到类似 <_sre.SRE_Match 对象在 0x01812220>
的东西,这不是很有用.
Lastly, I added .group()
to the end of the print
line because I think this is what you want. Otherwise, you'd get something like <_sre.SRE_Match object at 0x01812220>
, which isn't too useful.
这篇关于Re.match() 总是返回 none的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!