简体   繁体   English

Python Regex在开始时就可以匹配,但在结尾时不起作用

[英]Python Regex works for match at the beginning, but not at end

I am fairly new at python, but have used regex for a while. 我是python的新手,但是使用正则表达式已有一段时间了。 What am I missing here: 我在这里想念的是什么:

>>> 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'

Why does this match at the beginning of the string, but not at the end? 为什么在字符串的开头而不是结尾匹配? I am using python 2.7 on windows and linux. 我在Windows和Linux上使用python 2.7。

You should use search instead of match . 您应该使用search而不是match According to the docs: 根据文档:

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). Python根据正则表达式提供了两种不同的基本操作: re.match() 仅在字符串的开头检查匹配项,而re.search() 在字符串中的任何位置检查匹配项(这是Perl的默认操作) )。

So when you use match it's the same as using ^ in your regex (matches the position before the first character in the string). 因此,当您使用match它与在正则表达式中使用^相同(匹配字符串中第一个字符之前的位置)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM