Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách tìm tất cả matches của Regular Expression trong Python

Python cung cấp 2 phương thức chính để tìm tất cả matches non-overlapping của pattern trong string.

1. re.findall() - Trả về List

import re

text = 'TP Tutorials Point TP'

# Không capturing group -> list full matches
print(re.findall(r'TP', text))  # ['TP', 'TP']

# Có capturing group -> list group content
print(re.findall(r'(T)(P)', text))  # [('T', 'P'), ('T', 'P')]

2. re.finditer() - Trả về Iterator MatchObject


for match in re.finditer(r'TP', text):
    print(f'Match: {match.group()}, Position: {match.start()}-{match.end()}')
# Match: TP, Position: 0-2
# Match: TP, Position: 19-21

So sánh nhanh

Phương thứcTrả vềVị trí matchNamed groupsMemory
findall()List[str/tuple]KhôngKhó truy cậpLoad all
finditer()Iterator[Match]Có (.start/.end)Dễ (.groupdict())Lazy

Khi nào dùng cái nào?

  • findall(): Cần list kết quả đơn giản, input nhỏ, không cần vị trí.
  • finditer(): Cần vị trí, named groups, xử lý file lớn/stream, highlight, replace có điều kiện.

Bonus: Overlapping matches (khớp chồng chéo)

Regex mặc định không khớp chồng chéo. Dùng lookahead capturing group:


# Tìm tất cả 'aba' trong 'ababa' (overlapping)
text = 'ababa'
# Pattern: lookahead capture group
matches = [m.group(1) for m in re.finditer(r'(?=(aba))', text)]
print(matches)  # ['aba', 'aba']