Python: "re.match(pattern)"与 "re.search(' ^' + pattern)"之间的差异

标签 python regex

<分区>

在阅读文档时,我发现 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'>

关于Python: "re.match(pattern)"与 "re.search(' ^' + pattern)"之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48355460/

相关文章:

python - 带破折号的 Django/Python url 正则表达式

python - 在Python中分割多字标签的有效方法

python 异常处理

python - 正则表达式意外结束

类方法的Python单元测试

regex - RegEx 表达式中的字符失败

sql - 从 Oracle 字符串中删除特殊字符

python - Networkx 作为任务队列?

Python selenium iselementpresent 给出 "wrong"答案

javascript - 使用javascript在mvc路由的一部分中有效增加数字