Use VERBOSE mode for a documented local pattern
re.VERBOSE lets a regular expression be laid out across lines with indentation and comments. This is helpful for a local format whose parts need explanation. The example validates a synthetic inventory label: two uppercase letters, a hyphen, three digits, and an optional revision suffix such as -R2.
Whitespace outside character classes is ignored in verbose mode, so the spacing in the expression is for readers. The # comments explain each component. Anchors ensure the entire supplied label matches rather than merely finding a valid-looking substring inside a longer string. The assertions distinguish valid labels from common mistakes: lowercase letters, too few digits, and an incomplete revision.
A literal space that must be matched cannot simply be placed as visual spacing in this mode; it needs escaping or a character class. Likewise, an unescaped # begins a comment outside a character class. VERBOSE improves readability, but it does not change the underlying matching rules or guarantee that a format is appropriate for every domain. Keep the expression and its examples close to the format definition it implements.
re.VERBOSE is available in supported Python 3 releases; no newer API is used.
AI assistance disclosure: This article was drafted with AI assistance and checked against the cited Python documentation.
Sources: Python re.VERBOSE and Python re.fullmatch.
import re
local_label = re.compile(
r"""
^
[A-Z]{2} # warehouse zone
-
\d{3} # item number
(?:-R\d+)? # optional revision
$
""",
re.VERBOSE,
)
valid = ["AB-123", "ZX-007-R2"]
invalid = ["ab-123", "AB-12", "AB-123-R"]
assert all(local_label.fullmatch(value) for value in valid)
assert not any(local_label.fullmatch(value) for value in invalid)
for value in valid:
print(f"accepted={value}")
accepted=AB-123
accepted=ZX-007-R2