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

pythonserver side programmingprogramming

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

相关文章