Course outline · 0% complete

0/27 lessons0%

Course overview →

Groups, match, and replace

lesson 9-2 · ~11 min · 24/27

Capturing the pieces you care about

Parentheses create a capture group: the part of the match inside them is saved and numbered from 1, left to right.

  • string.match(regex) returns the full match at index 0, then each group.
  • string.replace(regex, replacement) can use $1, $2… in the replacement to reinsert groups.
  • Named groups read better: (?<year>\d{4}) is written back as $<year> and appears in match(...).groups.
  • The g flag makes match/replace handle every occurrence instead of just the first.

Groups are the regex you actually use at work: pulling fields out of logs and filenames, reshaping dates, mass-renaming in an editor. test only says whether text matches — groups let you keep the pieces.

Code exercise · javascript

Run it. Three groups capture the date parts, and replace reassembles them in a new order. The g-flag example rewrites every match in one call.

Quiz

Without the `g` flag, what does `"a-b-c".replace(/-/, "+")` return?

The practical regex kit

You now have the 95% kit used in real work: test for validation (anchored!), match to extract, replace with groups to reshape, and g for all occurrences. When you need every match with its groups, for (const m of str.matchAll(regex)) iterates them, and yes, that is the iteration protocol from lesson 7-1.

Interview advice: keep patterns small and readable, and narrate them piece by piece like the figure in lesson 9-1. Nobody expects regex golf.

Code exercise · javascript

Run it. matchAll yields every match WITH its groups. Each `m` works like the match array you already know: m[0] is the whole match, m[1] onward are the groups.

Code exercise · javascript

Your turn. Names arrive as `"Last, First"`. Use `replace` with two capture groups to flip them to `"First Last"`.