Regex Named Group Log Parsing
Turn unstructured log lines into typed dicts with named capture groups and one compiled pattern, rejecting malformed lines explicitly.
Code
import re
# 具名分组让提取逻辑自文档化;pattern 只编译一次
LINE = re.compile(
r'^(?P<ts>\\d{4}-\\d{2}-\\d{2}T[\\d:]+) '
r'(?P<level>INFO|WARN|ERROR) '
r'(?P<logger>[\\w.]+) - (?P<message>.*)$'
)
LOG_LINES = [
'2026-11-09T10:15:04 INFO app.api - request served in 42ms',
'2026-11-09T10:15:06 WARN app.db - pool at 80% capacity',
'this line is garbage',
'2026-11-09T10:16:00 ERROR app.worker - job 42 failed: timeout',
]
def parse(lines: list[str]) -> list[dict[str, str]]:
parsed = []
for line in lines:
match = LINE.match(line)
if match is None:
# 解析失败显式上报,而不是静默丢行
print(f'unparseable: {line[:40]}')
continue
parsed.append(match.groupdict())
return parsed
if __name__ == '__main__':
rows = parse(LOG_LINES)
for row in rows:
print(f"{row['level']:<5} {row['logger']:<8} {row['message']}")Output
Captured from a sandboxed run of this snippet in the build pipeline.
unparseable: 2026-11-09T10:15:04 INFO app.api - reque
unparseable: 2026-11-09T10:15:06 WARN app.db - pool a
unparseable: this line is garbage
unparseable: 2026-11-09T10:16:00 ERROR app.worker - jWhat the code does
Regex Named Group Log Parsing keeps everything in the function parse.
Iteration happens inside for line in lines — everything outside it runs once.
Applying it
The main signature reads def parse(lines: list[str]) -> list[dict[str, str]]
Output lines are prefixed (unparseable:), making each step’s effect easy to spot.
Statements that matter
if match is None:
# 解析失败显式上报,而不是静默丢行
print(f'unparseable: {line[:40]}')
continue
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
- What does Regex Named Group Log Parsing print when run?
- Invoke the file as-is — the `unparseable:` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.