如何在 Python 正则表达式中使用 re.finditer() 方法?

pythonserver side programmingprogramming更新于 2023/11/9 16:13:00

根据 Python 文档,

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



相关文章