Compile patterns you reuse
re.compile(pattern) returns a Pattern object that has all the same methods (.search, .findall, .sub, etc.) but skips the parsing step on each call. For patterns used in a loop or repeatedly across a function, compiling is faster.
Python actually caches compiled patterns automatically (last few unique ones). But explicit compilation is clearer code and guaranteed regardless of cache state.
The VERBOSE flag
re.VERBOSE (alias re.X) lets you write multi-line patterns with whitespace and comments. Inside the pattern:
- Whitespace is IGNORED (use
\s,\, or character class for literal space). #starts a comment to end of line.
This is the cure for unreadable regex. Any pattern beyond ~30 characters benefits.
Combining flags
Flags can be combined with |: re.compile(pattern, re.VERBOSE | re.MULTILINE | re.IGNORECASE).
Inline flags
Alternatively, set flags at the start of the pattern with (?flags): (?ix) at the start enables IGNORECASE and VERBOSE for the whole pattern. Also works as scoped (?ix:...) for a section.