Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

ความแตกต่างระหว่าง re.findall() และ re.finditer() ใน Python

re.findall()

ช่วยได้ list ของ pattern ที่จับคู่ทั้งหมด ค้นหาจากต้นหรือท้ายสตริง คืน occurrences ทั้งหมด แนะนำใช้เสมอ

ตัวอย่าง

import re
result = re.search(r'TP', 'TP Tutorials Point TP')
print(result.group())

ผลลัพธ์

TP

re.finditer()

re.finditer(pattern, string, flags=0) คืน iterator ให้ MatchObject instances ทุก non-overlapping matches สแกนซ้ายไปขวา คืนตามลำดับที่พบ รวม empty matches

ตัวอย่าง

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