liveBook · Manning

Noncapturing group

As explained in The Well-Grounded Rubyist, Fourth Edition

A non-capturing group groups a regular-expression subexpression for matching without storing its text as a numbered capture.

Use the (?:...) construct to group a regular-expression subexpression for matching without adding its text to the numbered captures. Unlike a zero-width assertion, the group consumes characters; it simply does not save them. section 11.5.3

Grouping without an extra capture

For str = "abc def ghi", /(abc) (?:def) (ghi)/.match(str) produces MatchData "abc def ghi" 1:"abc" 2:"ghi". The matched "def" participates in the full match but does not become capture 2.

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains syntax, character consumption, and MatchData capture numbering, contrasting groups with zero-width assertions.
Examples
Demonstrates /(abc) (?:def) (ghi)/ and its two numbered captures in Ruby MatchData.
What it assumes
Assumes regular-expression matching and numbered captures, while clarifying how grouping differs from zero-width assertions.
What you can do after
Apply it in Ruby regular expressions to group matching logic without shifting or storing an unwanted numbered capture.
How it connects
Connects regular-expression grouping with capturing groups, MatchData, and zero-width assertions.

Also explained in

Compare how 3 books explain noncapturing group →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.