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

Cách bắt exception (lỗi) từ Python Regular Expression

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ốngHành viXử lý
Pattern syntax errorRaise re.errortry/except re.error
Không tìm thấy matchTrả về Noneif match: check
Pattern hợp lệ, match rỗngTrả 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.