Module re chỉ ném exception re.error khi compile pattern thất bại (cú pháp sai). Không ném exception khi không tìm thấy match.
Exception: re.error
- Kích hoạt khi: pattern không hợp lệ (unmatched parentheses, invalid escape, bad quantifier...).
- Xảy ra tại compile time (
re.compile()hoặc lần đầu dùng pattern). - Không ném exception khi match thất bại (trả về
None).
Ví dụ: Bắt lỗi compile
import re
try:
pattern = re.compile(r'[a-z') # Thiếu ]
except re.error as e:
print(f'Regex error: {e}')
# Regex error: missing ], unterminated subpattern at position 4
Xử lý match thất bại (không phải exception)
pattern = r'\d+'
text = 'abc'
match = re.search(pattern, text)
if match:
print('Found:', match.group())
else:
print('Not found') # Không ném exception!
Best Practice: Compile sớm, bắt lỗi sớm
def safe_compile(pattern_str):
try:
return re.compile(pattern_str)
except re.error as e:
logger.error(f'Invalid regex pattern: {pattern_str} - {e}')
return None
# Sử dụng
compiled = safe_compile(user_input_pattern)
if compiled:
matches = compiled.findall(text)
Tóm tắt
| Tình huống | Hành vi | Xử lý |
|---|---|---|
| Pattern syntax error | Raise re.error | try/except re.error |
| Không tìm thấy match | Trả về None | if match: check |
| Pattern hợp lệ, match rỗng | Trả về Match object (empty) | match.group() == '' |
Không bao giờ dùng try/except quanh re.search() để bắt "không tìm thấy" - đó không phải exception.