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

Cách viết Python Regex dùng với re.findall()

re.findall() trả về list tất cả non-overlapping matches. Hành vi phụ thuộc vào việc pattern có capturing group hay không.

Quy tắc re.findall()

PatternTrả về
Không có capturing groupList các full match strings
Có 1 capturing groupList nội dung group 1
Có nhiều capturing groupsList các tuple (group1, group2, ...)
Non-capturing group (?:...)Không ảnh hưởng, trả về full match

Ví dụ

import re

text = 'TP Tutorials Point TP'

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

# Có group -> chỉ nội dung group
print(re.findall(r'(TP)', text))         # ['TP', 'TP']

# Nhiều groups -> tuple
print(re.findall(r'(T)(P)', text))       # [('T', 'P'), ('T', 'P')]

# Non-capturing -> full match
print(re.findall(r'(?:TP)', text))       # ['TP', 'TP']

Ví dụ thực tế: Extract email


text = 'Contact: user@example.com, admin@test.org'
# Capture toàn bộ email (không group con)
emails = re.findall(r'\b[\w.+-]+@[\w-]+\.[\w.-]+\b', text)
print(emails)
# ['user@example.com', 'admin@test.org']

# Capture user và domain riêng
parts = re.findall(r'\b([\w.+-]+)@([\w-]+\.[\w.-]+)\b', text)
print(parts)
# [('user', 'example.com'), ('admin', 'test.org')]

Mẹo: Dùng finditer() khi cần vị trí


for m in re.finditer(r'\d+', 'abc123def456'):
    print(f'Found {m.group()} at {m.start()}-{m.end()}')
# Found 123 at 3-6
# Found 456 at 9-12

Tóm tắt

  • findall() = extract data (list of strings/tuples).
  • finditer() = extract data + position (iterator of Match objects).
  • Kiểm soát output bằng capturing group / non-capturing group.
  • Raw string r'...' bắt buộc cho regex pattern.