Python re.error
The regex compiler rejects an unfinished character class.
A simple example
re.error
- Start with Pattern consisting of one open bracket
- Do this Compile the pattern
- Result Invalid pattern
Syntax
re.compile(rule)
Run these examples in Python
Save one example at a time as lesson.py. Use Python 3.9 or later.
python3 lesson.pyValidate a saved product search
A store lets staff save a regular expression for product labels. A buyer leaves an opening bracket unfinished, so the search editor should highlight the invalid rule before it is saved.
import re
try:
re.compile("[sale")
except re.error:
print("Fix the search pattern")
Fix the search pattern
The bracket opens a character class that never closes. The editor asks the buyer to fix it.
Save a costume search
A costume librarian groups two rack prefixes in a character class. Compile the pattern before saving the search. An incomplete character class must go back to the editor.
Catch a broken shelf filter
A clerk forgets the closing bracket in a saved shelf search. Compile the pattern before saving the search. An incomplete character class must go back to the editor.
What to watch for
Handle compilation errors when the user saves the rule so later searches use a validated pattern.