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.

PythonData Integrity

Code

pythonsnippet
35 lines
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

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`.