我是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。

最佳答案

您应该使用search而不是match。根据文档:


  Python提供了两种基于正则表达式的基本操作:re.match()仅在字符串的开头检查匹配项,而re.search()在字符串的任何位置检查匹配项(这是Perl的默认设置)。


因此,当您使用match时,它与在正则表达式中使用^相同(匹配字符串中第一个字符之前的位置)。

关于python - Python Regex在开始时就可以匹配,但在结尾时不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34438062/

10-12 12:56
查看更多