Python中可用的re.findall()和re.finditer()方法之间有什么区别?

re.findall()方法

re.findall()帮助获得所有匹配模式的列表。它从给定字符串的开始或结束进行搜索。如果我们使用findall方法在给定字符串中搜索一个模式,它将返回该模式的所有出现。在搜索模式时,建议始终使用re.findall(),它的工作方式类似于re.search()和re.match()。

示例

import re result = re.search(r'TP', 'TP nhooo.com 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