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

Các ví dụ cơ bản của Python Regular Expressions

Hai ví dụ cơ bản minh họa re.match() vs re.search().

Ví dụ 1: re.match() - Chỉ khớp đầu chuỗi

import re

text = 'TP Tutorials Point TP'

# Khớp 'TP' ở đầu
match = re.match(r'TP', text)
print(match)  # <_sre.SRE_Match object...>

# Không khớp 'Tutorials' ở đầu
match = re.match(r'Tutorials', text)
print(match)  # None

Ví dụ 2: re.search() - Khớp bất kỳ đâu


# Tìm 'Tutorials' ở giữa chuỗi
match = re.search(r'Tutorials', text)
print(match.group())  # 'Tutorials'

# Tìm 'TP' - trả về match ĐẦU TIÊN
match = re.search(r'TP', text)
print(match.group())  # 'TP' (vị trí 0)

Kết quả


Tutorials
TP

Nhận xét quan trọng

  • search() tìm thấy pattern ở bất kỳ vị trí nào.
  • search() chỉ trả về match đầu tiên (leftmost).
  • Để lấy tất cả: dùng findall() hoặc finditer().

Ví dụ bổ sung: re.findall()


# Lấy TẤT CẢ 'TP'
print(re.findall(r'TP', text))  # ['TP', 'TP']

# Lấy TẤT CẢ từ bắt đầu bằng T
print(re.findall(r'\bT\w+', text))  # ['TP', 'Tutorials', 'TP']

Tóm tắt khi dùng gì

CầnDùng
Kiểm tra prefix / validate format từ đầure.match() hoặc re.fullmatch()
Tìm pattern xuất hiện đầu tiênre.search()
Lấy tất cả matches (giá trị)re.findall()
Lấy tất cả matches (giá trị + vị trí + groups)re.finditer()