Python re
module 中的 search()
和 match()
函数有什么区别? ?
我已阅读 documentation ( current documentation ),但我似乎从来不记得它。我一直不得不查找并重新学习它。我希望有人会用例子清楚地回答它,以便(也许)它会留在我的脑海中。或者至少我会有一个更好的地方来回答我的问题,并且重新学习它需要更少的时间。
最佳答案
re.match
锚定在字符串的开头。这与换行无关,因此与在模式中使用 ^
不一样。
If zero or more characters at the beginning of string match the regular expression pattern, return a corresponding
MatchObject
instance. ReturnNone
if the string does not match the pattern; note that this is different from a zero-length match.Note: If you want to locate a match anywhere in string, use
search()
instead.
re.search
搜索整个字符串,如 the documentation says :
Scan through string looking for a location where the regular expression pattern produces a match, and return a corresponding
MatchObject
instance. ReturnNone
if no position in the string matches the pattern; note that this is different from finding a zero-length match at some point in the string.
所以如果你需要匹配字符串的开头,或者匹配整个字符串使用match
。它更快。否则使用搜索
。
文档有一个 specific section for match
vs. search
这也涵盖了多行字符串:
Python offers two different primitive operations based on regular expressions:
match
checks for a match only at the beginning of the string, whilesearch
checks for a match anywhere in the string (this is what Perl does by default).Note that
match
may differ fromsearch
even when using a regular expression beginning with'^'
:'^'
matches only at the start of the string, or inMULTILINE
mode also immediately following a newline. The “match
” operation succeeds only if the pattern matches at the start of the string regardless of mode, or at the starting position given by the optionalpos
argument regardless of whether a newline precedes it.
现在,说得够多了。是时候看一些示例代码了:
# 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
关于python - re.search 和 re.match 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/180986/