C.W.K.
Stream
Lesson 03 of 10 · published

Python re.compile() and re.VERBOSE

~8 min · python, compile, verbose

Level 0Pattern-Curious
0 XP0/90 lessons0/15 achievements
0/100 XP to next level100 XP to go0% complete

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.

Code

Compile and verbose·python
import re

# Reusable compiled pattern
EMAIL = re.compile(r'[\w.+-]+@[\w-]+\.[\w.-]+')

for line in lines:
    for match in EMAIL.finditer(line):
        print(match.group())

# Verbose mode for readability
DATE = re.compile(r'''
    (?P<year>\d{4})    # 4-digit year
    -
    (?P<month>\d{2})   # 2-digit month
    -
    (?P<day>\d{2})     # 2-digit day
''', re.VERBOSE)

m = DATE.match('2026-05-04')
print(m.groupdict())
# {'year': '2026', 'month': '05', 'day': '04'}

# Combining flags
LOG = re.compile(
    r'^ERROR:\s+(.*)$',
    re.MULTILINE | re.IGNORECASE
)

# Inline flags equivalent
LOG = re.compile(r'(?im)^ERROR:\s+(.*)$')

External links

Exercise

Take a regex from your code. Convert it to a compiled pattern at module level with VERBOSE mode and named groups. Verify the calling code is now self-documenting (m.group('name') instead of m.group(1)).

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.