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.

JavascriptData Integrity

Code

javascriptsnippet
20 lines
// 命名捕获组 + 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 lines

Inside 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

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