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

Tại sao dùng re.compile() trong Python Regular Expression

re.compile(pattern) biên dịch pattern thành Pattern Object (compiled regex), cho phép reuse nhiều lần mà không cần parse lại pattern string.

Ví dụ

import re

# Compile một lần
pattern = re.compile(r'TP')

# Dùng nhiều lần
text1 = 'TP Tutorialspoint TP'
text2 = 'TP is most popular tutorials site of India'

print(pattern.findall(text1))  # ['TP', 'TP']
print(pattern.findall(text2))  # ['TP']

Kết quả


['TP', 'TP']
['TP']

Lợi ích của re.compile()

Lợi íchGiải thích
Hiệu năngTránh parse/compile pattern lặp lại. Cache internal cũng giúp nhưng compile tường minh rõ ràng hơn.
Độ đọc codeTách pattern definition khỏi usage. Dễ bảo trì, đổi pattern 1 chỗ.
FlagsGắn flags lúc compile: re.compile(pattern, re.IGNORECASE | re.MULTILINE).
MethodsPattern object có methods: match(), search(), findall(), finditer(), sub(), split().

Khi nào NÊN compile

  • Pattern dùng trong loop hoặc gọi nhiều lần.
  • Pattern phức tạp, compile tốn thời gian.
  • Module-level constants (compile khi import).

Khi nào KHÔNG cần compile

  • Pattern dùng 1 lần (one-off).
  • Pattern đơn giản, compile nhanh.
  • Python internal cache (512 entries) đã handle tự động.

Module-level pattern (Best Practice)


# constants.py
import re

EMAIL_RE = re.compile(r'\b[\w.+-]+@[\w-]+\.[\w.-]+\b')
PHONE_RE = re.compile(r'(?:\+84|0)[35789]\d{8}')
DATE_RE = re.compile(r'\d{4}-\d{2}-\d{2}')

# usage.py
from constants import EMAIL_RE

emails = EMAIL_RE.findall(text)

Kết luận

re.compile() không bắt buộc nhưng là best practice cho pattern dùng lặp, phức tạp, hoặc cần flags. Code rõ ràng, dễ maintain, hiệu năng tốt.