Python中re.findall()和re.finditer()方法有什么区别?
阅读更多:Python 教程
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
re.finditer()方法
re.finditer(pattern, string, flags=0)
返回一个迭代器,该迭代器在字符串中提供RE模式的所有不重叠匹配项的MatchObject实例。该字符串是从左到右扫描的,并且按照发现的顺序返回匹配项。结果包括空匹配。
以下代码展示了在Python中使用re.finditer()方法的示例。
示例
import re s1 = 'Blue Berries'
pattern = 'Blue Berries'
for match in re.finditer(pattern, s1):
s = match.start()
e = match.end()
print 'String match "%s" at %d:%d' % (s1[s:e], s, e)
输出
Strings match "Blue Berries" at 0:12