Python正则表达式在开始时适用于match,但在结束时不适用

2024-09-27 04:22:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我对python还相当陌生,但已经使用regex一段时间了。我错过了什么:

>>> 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上使用python2.7。你知道吗


Tags: importrematchgroupresultsatregexpattern
1条回答
网友
1楼 · 发布于 2024-09-27 04:22:38

您应该使用^{}而不是^{}。根据文件:

Python offers two different primitive operations based on regular expressions: re.match() checks for a match only at the beginning of the string, while re.search() checks for a match anywhere in the string (this is what Perl does by default).

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

相关问题 更多 >

    热门问题