Regular expressions, groups & matchAll
Parse text with named groups
Lesson 17 of 20 · 11 min · Module 5: Real-world data
Logs, CSV exports, and chat commands are text with a structure. Regular expressions with named groups turn such text into objects you can work with.
Start this lesson →Free. No installation: you write and run the code in your browser, and it is checked automatically.
By the end, you’ll be able to…
- Capture fields with named groups
- Anchor a pattern to the whole line
- Turn text into structured data
The idea
(?<level>[A-Z]+) captures part of a match under a name, available as match.groups.level. Anchor a pattern with ^ and $ so the whole line must match. text.matchAll(/…/g) returns every match in a text.
const m = "[email protected]".match(/^(?<user>[^@]+)@(?<domain>.+)$/);
console.log(m.groups.user, m.groups.domain);
01Names beat positions
match[3] breaks as soon as someone adds a group earlier in the pattern. match.groups.level keeps working and explains itself.
02Anchors matter
Without ^ and $, the pattern would match a valid-looking part of "junk 2026-10-18 …" and accept a broken line. Anchors require the entire line to fit.
console.log(/\d+/.test("abc123"), /^\d+$/.test("abc123"));true false03Define the pattern once
A regular expression stored in a constant is created once and reused for every line, which keeps the parser fast and the pattern in one place.
Your turn
parseLogLine(line) for lines like 2026-10-18 08:07:03 ERROR Payment service timeout, returning { date, time, level, message }, or null when the line does not match (levels are uppercase words; there may be several spaces after the level). Write countLevels(text) that returns an object counting each level across all lines, ignoring lines that do not match.What the checks look for
- Parses a log line into named fields
- Allows several spaces after the level
- Returns null for lines that do not match
- Counts levels and skips other lines
Take this with you
Named groups turn lines of text into objects.
Go a little further
Return the messages of all ERROR lines between two given times.