re.match和re.search与'^'有何不同?

时间:2017-08-14 15:17:38

标签: python regex

似乎re.match和re.search w /'^'是相同的,除了re.search 可以使用re.MULTILINE标志,使其更加灵活。

string ="""U.S. stock-index futures pointed
to a solidly higher open on Monday
North Korea. That issue overshadowed the state of 
the equity market, where earnings 
have been strong at a time of high 
employment and low inflation, 
as well as valuations that a
ppear elevated by many metrics, north korea"""

import re


re.search('^North Korea\.?', string)  # no match
re.match('^North Korea\.?', string) # no match
re.search('^North Korea\.?', string, flags = re.MULTILINE ).group() #match

使用一个优于另一个有什么好处吗?

1 个答案:

答案 0 :(得分:0)

re.match()仅在开头检查匹配

>>> re.match("c", "abcdef")    # No match
>>> re.search("c", "abcdef")   # Match
<_sre.SRE_Match object at ...>

re.search()检查字符串中任何位置的匹配项。如果要查找子字符串,请使用re.search()

>>> re.match("c", "abcdef")    # No match
>>> re.search("^c", "abcdef")  # No match
>>> re.search("^a", "abcdef")  # Match
<_sre.SRE_Match object at ...>

这两种情况,搜索和匹配都会做同样的事情,因为^

^(Caret。)匹配字符串的开头。因此,它强制re.search从字符串的开头搜索(没有MULTILINE)。

^和MULTILINE,re.search()re.match()不同,因为:

re.match()只能从字符串的开头找到。因此,如果第一行不匹配,则不匹配。

re.search()匹配字符串上的任何位置,因此,它可以匹配第二,第三,......新行。

document中,它说

  

但请注意,在MULTILINE模式下,match()仅匹配   字符串的开头,而使用带有常规的search()   以'^'开头的表达式将在每个开头匹配   线。

相关问题