Python中re.match()、re.search()和re.findall()方法有什么区别?
re.match()、re.search()和re.findall()都是Python模块re的方法。
阅读更多:Python 教程
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