liveBook · Manning

Regex grouping

As explained in Secrets of the JavaScript Ninja, Third Edition

A capturing group is a parenthesized regular-expression subpattern whose matched text is stored for later extraction or reference.

Need the hours and minutes from a time such as `23:45`, not just the whole time? Put each part of the regular expression in parentheses: `(\d{2}):(\d{2})`. Parentheses group terms into a unit and, by default, capture the text that unit matches. section 12.2.2 section 12.4.1

Extract a time

`const [whole, hours, minutes] = "Strike at 23:45!".match(/(\d{2}):(\d{2})/);` gives `"23:45"`, `"23"`, and `"45"`. Index 0 holds the full match; later indexes hold captures in opening-parenthesis order. section 12.4.1

A few rules make groups useful beyond simple extraction:

  • Group before applying a repetition operator: `/(ab)+/` matches one or more consecutive `ab` sequences. Alternation can likewise sit inside a group: `/(ab|cd)+/`. section 12.2.2
  • Nested captures are numbered by their opening parentheses. Use `(?:...)` when a group must shape the pattern but should not occupy a capture slot; add `?` after a group to make it optional. An unmatched optional capture is `undefined`. section 12.4.1
  • A backreference such as `\1` must match the exact text captured by group 1. `/\b([a-z]+) \1\b/i` finds a repeated word such as `doki doki`, rather than merely two words of the same shape. section 12.4.3
  • If a capturing group is repeated, its capture is the last result. Capturing rather than noncapturing does not itself remove the backtracking risk of a pattern with many possible matches. section 12.6.3

Choose the string method with care. With a local regex, `match` returns the full match and its captures. With the `g` flag, `match` instead returns full matches without captures. Use `matchAll` to iterate over global matches while retaining each match’s captures; it computes results lazily as you iterate. section 12.4.2

Listing 12.6 Finding multiple matches with a global regex
const ninjaRoster =
  "Hattori of Iga, Yoshi of Koga, Fuma of Hojo";
const titleRegex = /([^\s,]+) of ([^\s,]+)/g; #A

for (const found of ninjaRoster.matchAll( #B
  titleRegex, #B
)) { #B
  const [, name, clan] = found; #C
  console.log(
    `${name} hails from the ${clan} clan`,
  );
}

The global roster example uses `matchAll` and array destructuring to extract two captures from each match. section 12.4.2

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Explains capture indexing, nesting, optional and noncapturing groups, plus local-versus-global extraction behavior.
Examples
Uses time extraction, optional name-and-clan parsing, global roster matching, and repeated-word detection.
What it assumes
Assumes familiarity with JavaScript strings and arrays while defining capture ordering and noncapturing syntax.
What you can do after
Apply it via JavaScript String.match and String.matchAll to extract captures, and use backreferences to recognize repeated text.
How it connects
Connects grouping to quantifiers, alternation, and backreferences.

Also explained in

Compare how 7 books explain regex grouping →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Third Edition. The section links point to the parts of the book it draws on.