Python的re.search和re.match有什么区别?
Python re模块中的search()和match()函数有什么区别?
我读过文档 ( 目前的文档 ),但我似乎从来没有记住它。 我一直不得不查看并重新学习它。 我希望有人会用例子来清楚地回答这个问题,以便(也许)它会坚持在我的脑海中。 或者至less我会有一个更好的地方来回答我的问题,这将需要更less的时间来重新学习它。
re.match被锚定在string的开头。 这与换行无关,因此与在模式中使用^ 。
正如re.match文档所说:
如果string开头的零个或多个字符与正则expression式模式匹配,则返回相应的
MatchObject实例。 如果string与模式不匹配则返回None; 请注意,这与零长度匹配不同。注意:如果您想在string中的任何位置find匹配项,请使用
search()。
re.searchsearch整个string,如文档所述 :
扫描string查找正则expression式模式产生匹配的位置,并返回相应的
MatchObject实例。 如果string中没有位置与模式匹配,则返回None; 请注意,这与在string中的某个位置查找零长度匹配不同。
所以如果你需要在string的开头匹配,或匹配整个string使用match 。 这是更快。 否则使用search 。
该文档具有特定部分的match与search ,也包括多行string:
Python提供了基于正则expression式的两种不同的基本操作:
match只在string的开头进行match检查,而search检查string中任何地方的匹配(这是Perl默认的做法)。请注意,即使使用以
'^'开头的正则expression式,match也可能与search不同:'^'只匹配string的开头,或者紧跟在换行符后面的MULTILINE模式中。 只有当模式匹配string的开始而不pipe模式,或者在可选的pos参数给出的开始位置(无论在其之前是否有新行)时,“match”操作才会成功。
现在,说够了。 时间看一些示例代码:
# example code: string_with_newlines = """something someotherthing""" import re print re.match('some', string_with_newlines) # matches print re.match('someother', string_with_newlines) # won't match print re.match('^someother', string_with_newlines, re.MULTILINE) # also won't match print re.search('someother', string_with_newlines) # finds something print re.search('^someother', string_with_newlines, re.MULTILINE) # also finds something m = re.compile('thing$', re.MULTILINE) print m.match(string_with_newlines) # no match print m.match(string_with_newlines, pos=4) # matches print m.search(string_with_newlines, re.MULTILINE) # also matches
search ⇒findstring中的任何地方并返回一个匹配对象。
match ⇒在string的开头find一些东西并返回一个匹配对象。
re.search在整个string中search模式,而re.match不search模式; 如果没有,就没有别的select,只能在string开头匹配 。
你可以参考下面的例子来了解re.match和re.search的工作
a = "123abc" t = re.match("[az]+",a) t = re.search("[az]+",a)
re.match将返回none,但re.search将返回abc。
不同的是, re.match()误导任何习惯于Perl , grep或sed正则expression式匹配的人,而re.search()则不会。 🙂
更为清醒的是, 正如约翰·D·库克 re.match() John D. Cook)所言 , re.match() “performance得好像每个模式都有前缀。 换句话说, re.match('pattern')等于re.search('^pattern') 。 所以它锚定一个模式的左侧。 但是它也不能固定一个模式的右侧:这仍然需要终止$ 。
坦白地说,上面,我认为re.match()应该被弃用。 我有兴趣知道应该保留的原因。
re.match尝试匹配string开头的模式。 re.search尝试匹配整个string中的模式,直到find匹配。