liveBook · Manning

Non-capturing group

As explained in Secrets of the JavaScript Ninja, Third Edition

A non-capturing group is a parenthesized regular-expression subpattern that groups terms without storing its matched text as a capture.

Use a non-capturing group when parentheses should group regex terms but their matched text should not appear as a capture. Add `?:` immediately after the opening parenthesis: `(?:pattern)`. This changes the match array, not what the pattern matches. section 12.4.1

In practice:

  • `(?: of (\S+))?` groups the optional ` of ` and clan-name pattern without capturing the whole group; the inner ` (\S+)` still captures the clan name. section 12.4.1
  • Omitting `?:` lets the group capture. With a repeated capturing group, the capture holds its last result; use a non-capturing group when that value is not needed. section 12.6.3

An optional clan name

In `/(\S+)(?: of (\S+))?/`, matching `Hattori of Iga` gives the full match, `Hattori`, and `Iga` as the match array’s three entries. Matching `Yoshi` leaves the clan capture `undefined`; the non-capturing group adds no entry. section 12.4.1

Listing 12.5 Nested, optional, and non-capturing groups
const ninjaTitleRegex = /(\S+)(?: of (\S+))?/; #A
const ninjaTitle = "Hattori of Iga";
const found = ninjaTitle.match(ninjaTitleRegex); #B

if (found === null) {
  console.assert(false, "Match expected");
} else {
  const [match, name, clan] = found; #C
  console.assert(
    match === "Hattori of Iga",
    "The full match is 'Hattori of Iga'",
  );
  console.assert(
    name === "Hattori",
    "The first capture group is 'Hattori'",
  );
  console.assert(
    clan === "Iga",
    "The second capture group is 'Iga'",
  );
}

See the complete JavaScript example and its assertions for the full match and individual captures. section 12.4.1

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Explains `?:` syntax, nested captures, optional groups, and repeated-group behavior without detailing regex-engine internals.
Examples
Uses an optional ninja clan name and a repeated word-and-whitespace pattern to demonstrate non-capturing groups.
What it assumes
Assumes familiarity with regex groups and match results; defines how `?:` changes capture output.
What you can do after
Understand how to group regex terms without adding an unwanted capture to the match array.
How it connects
Connects non-capturing groups to capturing groups, optional groups, match arrays, and regular expressions.

Also explained in

Compare how 4 books explain non-capturing group →

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.