我是 python 的新手,但使用正则表达式已有一段时间了。我在这里缺少什么:
>>> import re
>>> raceResuls = "2014 Results at:"
>>> raceDate = "Saturday, December 5, 2015"
>>> pattern = re.compile("(\d{4})")
>>> pattern.match(raceResuls).group(1)
'2014'
>>> pattern.match(raceDate).group(1)
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
pattern.match(raceDate).group(1)
AttributeError: 'NoneType' object has no attribute 'group'
为什么这个匹配在字符串的开头,而不是结尾?我在 Windows 和 Linux 上使用 Python 2.7。
请您参考如下方法:
Python offers two different primitive operations based on regular expressions:
re.match()checks for a match only at the beginning of the string, whilere.search()checks for a match anywhere in the string (this is what Perl does by default).
因此,当您使用match 时,它与使用^ 是一样的在你的正则表达式中(匹配字符串中第一个字符之前的位置)。
