python - re.match vs. re.search [duplicate]

时间:2021-12-31 20:27:45

Possible Duplicate:
What is the difference between Python’s re.search and re.match?

可能重复:Python的re.search和re.match有什么区别?

I have recently been jumping into understanding regex with python.

我最近刚刚开始理解regex和python。

I have been looking at the api; I can't seem to understand the difference between:

我一直在研究这个api;我似乎无法理解这两者之间的区别:

re.match vs. re.search

re.match与re.search

when is it best to use each of these? pros? cons?

什么时候最好使用它们?优点呢?缺点呢?

Please and thank you.

请和谢谢。

3 个解决方案

#1


56  

re.match() matches only from the beginning of the string. A common gotcha. See the documentation.

匹配()仅从字符串的开始处匹配。一个共同的问题。见文档。

#2


37  

From search() vs. match():

从搜索()和匹配():

re.match() checks for a match only at the beginning of the string, while re.search() checks for a match anywhere in the string.

re.match()只在字符串的开头检查匹配,而re.search()检查字符串中的任何地方是否匹配。

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

#3


7  

I just learned that you can also search for substrings like this:

我刚知道你也可以搜索像这样的子字符串:

if 'c' in 'abcdef'
# True

#1


56  

re.match() matches only from the beginning of the string. A common gotcha. See the documentation.

匹配()仅从字符串的开始处匹配。一个共同的问题。见文档。

#2


37  

From search() vs. match():

从搜索()和匹配():

re.match() checks for a match only at the beginning of the string, while re.search() checks for a match anywhere in the string.

re.match()只在字符串的开头检查匹配,而re.search()检查字符串中的任何地方是否匹配。

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

#3


7  

I just learned that you can also search for substrings like this:

我刚知道你也可以搜索像这样的子字符串:

if 'c' in 'abcdef'
# True