Catch re.error for a supplied local pattern
A pattern supplied through a local configuration field or command-line option can be syntactically invalid. re.compile() converts pattern text into a regular-expression object and raises re.error when compilation encounters an invalid expression. This example uses two synthetic strings: r"item-\d+", which can match item-42, and r"(item-\d+", which has an unmatched opening parenthesis.
check_local_pattern() compiles the supplied text before attempting a search. If compilation succeeds, pattern.search(sample) returns a match object or None; converting that result with bool() produces the stable True value included in the success message. If compilation raises re.error, the helper returns invalid instead. The assertions check the two concrete outcomes before the program prints them. The output deliberately omits an exception message because diagnostic wording and positions may differ across Python releases.
Catching re.error here only classifies a failure raised while compiling this supplied pattern. A successfully compiled expression can still describe the wrong business rule, and this assertion does not prove that it matches every intended input. Complex regular expressions may also have undesirable matching costs on some text, so applications accepting untrusted patterns need separate limits or a constrained pattern design.
The example uses APIs available in supported Python 3 releases. Python 3.13 introduced the re.PatternError name; re.error remains its backward-compatible alias.
AI assistance disclosure: This article was drafted with AI assistance and checked against the cited Python documentation.
Sources: Python re.PatternError exception and Python re.compile.
import re
def check_local_pattern(pattern_text, sample):
try:
pattern = re.compile(pattern_text)
except re.error:
return "invalid"
return f"valid match={bool(pattern.search(sample))}"
valid_result = check_local_pattern(r"item-\d+", "item-42")
invalid_result = check_local_pattern(r"(item-\d+", "item-42")
assert valid_result == "valid match=True"
assert invalid_result == "invalid"
print(valid_result)
print(invalid_result)
valid match=True
invalid