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

วิธีใช้ re.finditer() ใน Python Regular Expression

ตามเอกสาร Python:

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