python - re.search 和 re.match 有什么区别?

标签 python regex search match

Python re module 中的 search()match() 函数有什么区别? ?

我已阅读 documentation ( current documentation ),但我似乎从来不记得它。我一直不得不查找并重新学习它。我希望有人会用例子清楚地回答它,以便(也许)它会留在我的脑海中。或者至少我会有一个更好的地方来回答我的问题,并且重新学习它需要更少的时间。

最佳答案

re.match 锚定在字符串的开头。这与换行无关,因此与在模式中使用 ^ 不一样。

作为 re.match documentation说:

If zero or more characters at the beginning of string match the regular expression pattern, return a corresponding MatchObject instance. Return None 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. Return None 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, while search checks for a match anywhere in the string (this is what Perl does by default).

Note that match may differ from search even when using a regular expression beginning with '^': '^' matches only at the start of the string, or in MULTILINE 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 optional pos 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/

相关文章:

regex - RE2 RegEx-斜线两侧的数字相同

java - 使用二分查找在数组中查找值 (Java)

python - 了解非平凡情况下生成器内部的 StopIteration 处理

java - 正则表达式 - 在 `:` 上分割字符串,但不在 if 语句内分割字符串

regex - 简化正则表达式量词

PHP MySQL 搜索脚本 - 只匹配某些字母

java - 搜索数组的问题

python - 使用 scipy truncnorm 拟合数据

python - 在 cronjob 上运行结构脚本

python - 如何在 Mac OS X 上确定 python 模块搜索路径?