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


根據 Python 文件,

re.finditer(pattern, string, flags=0)

返回一個迭代器,為字串中 RE 模式的所有非重疊匹配生成 MatchObject 例項。從左到右掃描字串,並按找到的順序返回匹配項。結果中包括空匹配。 

以下程式碼展示了 re.finditer() 方法在 Python 正則表示式 中的使用

示例

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

更新於: 02-11-2023

18K+ 次瀏覽

開啟您的事業

完成教程獲得認證

開始使用
廣告
© . All rights reserved.