matchAll Named Groups Parse Log Lines
Extract typed fields from log lines with matchAll and named capture groups, so every match carries self-documenting keys instead of fragile array indexes.
Code
// 命名捕获组 + matchAll:每条命中都带自说明的字段名
const pattern = /(?<time>\d{2}:\d{2}:\d{2}) (?<level>INFO|WARN|ERROR) (?<message>.+)/g;
const logText = `09:30:01 INFO cache warmed in 42ms
09:30:07 WARN retry budget at 80%
09:31:00 ERROR upstream timeout
not a log line`;
const entries = [...logText.matchAll(pattern)].map(({ groups }) => ({
time: groups.time,
level: groups.level,
message: groups.message,
}));
for (const { time, level, message } of entries) {
console.log(time, '[' + level + ']', message);
}
// 命名组让下游代码免于脆弱的下标访问;不匹配的行直接被跳过
console.log('parsed', entries.length, 'of 4 lines');Output
Captured from a sandboxed run of this snippet in the build pipeline.
09:30:01 [INFO] cache warmed in 42ms
09:30:07 [WARN] retry budget at 80%
09:31:00 [ERROR] upstream timeout
parsed 3 of 4 linesInside the snippet
Repetition is confined to for (const { time, level, message } of entries) — the rest of the file is straight-line.
Top-level bindings pattern, logText, entries hold the demo state — nothing sits inside a function scope.
Using it
Look for the parsed prefixes when the file runs; they tie each line to its step.
Key statements
const entries = [...logText.matchAll(pattern)].map(({ groups }) => ({
time: groups.time,
level: groups.level,
message: groups.message,
}));
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.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.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.
FAQ
- Are there third-party dependencies?
- No. The dependency list is empty; the code stays inside the standard library. Its state lives in module-level bindings: `pattern`, `logText`, `entries`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.