在阅读文档时,我发现 re.match()
之间的全部区别和 re.search()
是那个re.match()
仅从字符串的开头开始检查。
>>> import re
>>> a = 'abcde'
>>> re.match(r'b', a)
>>> re.search(r'b', a)
<_sre.SRE_Match object at 0xffe25c98>
>>> re.search(r'^b', a)
>>>
我有什么误解吗,或者 re.search('^' + pattern)
之间没有任何区别吗?和 re.match(pattern)
?
只使用 re.search()
是一个好习惯吗? ?
你应该看看Python's re.search()
vs. re.match()
明确提到另一个区别的文档是:
Note however that in MULTILINE
mode match()
only matches at the beginning of the string, whereas using search()
with a regular expression beginning with '^' will match at the beginning of each line.
>>> re.match('X', 'A\nB\nX', re.MULTILINE) # No match
>>> re.search('^X', 'A\nB\nX', re.MULTILINE) # Match
<_sre.SRE_Match object; span=(4, 5), match='X'>
第一个区别(对于 future 的读者)是:
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).
For example:
>>> re.match("c", "abcdef") # No match
>>> re.search("c", "abcdef") # Match
<_sre.SRE_Match object; span=(2, 3), match='c'>
以'^'开头的正则表达式可以与 search()
一起使用限制字符串开头的匹配:
>>> re.match("c", "abcdef") # No match
>>> re.search("^c", "abcdef") # No match
>>> re.search("^a", "abcdef") # Match
<_sre.SRE_Match object; span=(0, 1), match='a'>