什么是Python正则表达式中re.search()方法和re.findall()方法的区别?
re.search()方法与re.match()类似,但它不限于仅在字符串开头找到匹配项。
阅读更多:Python 教程
示例
import re
result = re.search(r'Tutorials', 'TP Tutorials Point TP')
print result.group()
输出
Tutorials
在这里,您可以看到search()方法能够从字符串的任何位置找到一个模式。
re.findall()帮助获得所有匹配模式的列表。它从给定字符串的开头或结尾开始搜索。如果我们使用findall方法在给定字符串中搜索模式,则会返回模式的所有出现。在搜索模式时,建议始终使用re.findall(),它的作用类似于re.search()和re.match()。
示例
import re
result = re.search(r'TP', 'TP Tutorials Point TP')
print result.group()
输出
TP