包含$的字符串在Python中找不到

时间:2012-08-08 23:11:55

标签: python regex

我遇到了python中正则表达式匹配的意外困难: 正如所料:

>>> re.match("r", "r").group() #returns...
"r"

然而:

>>>re.match("r", "$r").group()
Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'group'

有人知道为什么美元符号在匹配的字符串中会引起麻烦,以及如何解决这个问题?

1 个答案:

答案 0 :(得分:4)

查看re.matchre.search

之间的区别
>>> re.match("r", "$r")    # no match since re.match is equivalent to '^r'
>>> re.search("r", "$r")   # match
<_sre.SRE_Match object at 0x10047d3d8>

re.match从字符串的BEGINNING中搜索,因此“r”与“$ r”不匹配,因为“$ r”不以“r”开头。

re.search扫描字符串,因此它不依赖于字符串的开头。

作为一般形式,您应该以这种方式进行匹配:

match=re.search(pattern, string)
if match
   # you have a match -- get the groups...
else:
   # no match -- deal with that...