Python正则表达式与证明匹配不匹配

时间:2016-04-08 16:25:51

标签: python regex

我无法将#4356re.compile('#[0-9]+')匹配,而pythex.org显示它确实匹配。

regex = re.compile('#[0-9]+')
print re.match(regex, ' #4356')
None

告诉我我错过了什么?

2 个答案:

答案 0 :(得分:0)

也许你没有正确使用re.match。请查看随附的屏幕截图

enter image description here

re.match函数在成功时返回匹配对象,在失败时返回None。 请参阅以下链接,以便更好地了解如何使用re.match功能以及许多其他功能。

http://www.tutorialspoint.com/python/python_reg_expressions.htm

希望这能回答你的问题。一切顺利。

编辑:哦,是的,正如爱德华在评论中提到的那样。您在print re.match(regex, ' #4356')中添加了空格    这导致了这个问题。您可能希望将正则表达式更改为'\ s#[0-9] +'或者可以使用re.search。细节与我提到的链接相同!

答案 1 :(得分:0)

问题是你的字符串以空格开头,但re.match必须从字符串的开头匹配。您可以re.search或考虑正则表达式中的空格。

>>> import re
>>> regex = re.compile('#[0-9]+')
>>> re.match(regex, ' #4356')
>>> re.match(regex, '#4356')
<_sre.SRE_Match object at 0x7fc453c69370>
>>> re.search(regex, ' #4356')
<_sre.SRE_Match object at 0x7fc453c693d8>

通常我们不会将正则表达式对象传递给re.match等等...... regexmatchsearch方法可以直接使用。

>>> regex.search(' #4356')
<_sre.SRE_Match object at 0x7fc453c69370>

或者您可以将字符串传递给re.matchre.search等等......

>>> re.search('#[0-9]+', ' #4356')
<_sre.SRE_Match object at 0x7fc453c693d8>