Python 中的 re.match()、re.search() 和 re.findall() 方法有什么区别?
pythonserver side programmingprogramming
re.match()、re.search() 和 re.findall() 是 Python 模块 re 的方法。
re.match() 方法
如果匹配出现在字符串开头,re.match() 方法会查找匹配项。例如,对字符串 ‘TP Tutorials Point TP’ 调用 match() 并查找模式 ‘TP’ 将会匹配。
示例
import re result = re.match(r'TP', 'TP Tutorials Point TP') print result.group(0)
输出
TP
re.search() 方法
re.search() 方法类似于 re.match(),但它并不限制我们仅在字符串开头查找匹配项。
示例
import re result = re.search(r'Tutorials', 'TP Tutorials Point TP') print result.group(0)
输出
Tutorials
re.findall() 方法
re.findall() 有助于获取所有匹配模式的列表。它从给定字符串的开头或结尾进行搜索。如果我们使用 findall 方法在给定字符串中搜索模式,它将返回该模式的所有出现位置。在搜索模式时,建议始终使用 re.findall(),它的工作方式与 re.search() 和 re.match() 相同。
示例
import re result = re.search(r'TP', 'TP Tutorials Point TP') print result.group()
输出
TP
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

