Python 的 re.findall() 和 re.finditer() 方法有什麼區別?


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

更新於:2020年2月20日

911 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.