re.VERBOSE Keeps Complex Patterns Readable
The re.VERBOSE flag ignores whitespace and # comments inside a pattern, so multi-line regexes document their groups and still match exactly the same text.
Code
import re
# re.X(VERBOSE)忽略空白与 # 注释,正则可以分行排布并带说明
PATTERN = re.compile(
r"""
^ # 整行锚定
(?P<date>\d{4}-\d{2}-\d{2}) # 日期
\s+
(?P<level>INFO|WARN|ERROR) # 级别
\s+
(?P<msg>.+)$ # 余下全文
""",
re.VERBOSE,
)
lines = [
"2026-03-01 WARN disk usage at 91%",
"2026-03-01 ERROR checkout failed: timeout",
"not a log line",
]
for line in lines:
m = PATTERN.match(line)
if m:
print(m.group("date"), m.group("level"), "->", m.group("msg"))
else:
print("skip:", line)
# VERBOSE 下空白默认被忽略:要匹配字面空格必须转义或用 [ ]
spaced = re.compile(r"a\ b", re.VERBOSE)
class_re = re.compile(r"[aeiou]", re.VERBOSE | re.IGNORECASE)
print("escaped space matches:", bool(spaced.fullmatch("a b")))
print("flags combine with |:", class_re.findall("AEio"))Output
Captured from a sandboxed run of this snippet in the build pipeline.
2026-03-01 WARN -> disk usage at 91%
2026-03-01 ERROR -> checkout failed: timeout
skip: not a log line
escaped space matches: True
flags combine with |: ['A', 'E', 'i', 'o']How it works
A single loop drives the file — for line in lines.
Everything operates on top-level bindings: lines, spaced, class_re.
Points of care
- Self-contained — no imports beyond what the runtime already provides.
Using it
Running the file prints labeled results such as skip:, escaped space matches:, flags combine with |: — each operation’s effect is visible in the output.
Key statements
for line in lines:
m = PATTERN.match(line)
if m:
print(m.group("date"), m.group("level"), "->", m.group("msg"))
else:
print("skip:", line)
Interactive Tools for This Topic
Regular Expression TesterTest regular expressions against sample text with live match highlighting, capture group extraction, and flags support for global, case-insensitive, and multiline modes.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Nginx Location Block TesterTest any URL path against Nginx location blocks using authentic Nginx precedence (= exact, ^~ prefix, regex ~ and ~*, and longest prefix) with trace output.Regex Backreference ExplainerScan a regular expression to list its capturing groups, named groups, non-capturing groups, and backreferences, with warnings for dangling references.
FAQ
- Is there an install step between copy and run?
- No. Between copying and running there is nothing left to do. Every import resolves inside the standard library — `re`. Its state lives in module-level bindings: `lines`, `spaced`, `class_re`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.