Glossary

Capture group

A capture group is a parenthesized sub-pattern within a regular expression — (...) — whose matched text is remembered separately from the overall match, so it can be extracted, referenced later in the same pattern, or used in a replacement string. It's one of the core building blocks that turns regex from a yes/no "does this match" tool into one that can pull structured pieces out of text.

How it works

Groups are numbered left to right by their opening parenthesis, starting at 1 (group 0 is conventionally the entire match). A named group, (?<name>...), lets you reference the capture by name instead of position — much easier to read and maintain once a pattern has more than two or three groups. A non-capturing group, (?:...), groups a sub-pattern for applying a quantifier or alternation without allocating a numbered capture — useful when you need grouping but don't need to extract that piece.

Pattern: (\d{4})-(\d{2})-(\d{2})
Input:   "2026-09-29"
Group 1: "2026"   Group 2: "09"   Group 3: "29"

Pattern (named): (?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})

A backreference, \1 (or \k<name> for a named group), refers back to whatever a capture group actually matched, inside the same pattern — (\w+)\s+\1 matches a repeated word like "the the" because \1 must match the identical text group 1 captured, not just the same pattern.

Common pitfalls

  • Non-capturing groups ((?:...)) are easy to forget when you only need grouping for alternation or quantification — every unnecessary capturing group adds noise to the result array and a small performance cost.
  • Group numbering shifts if you add or remove a group earlier in the pattern — named groups avoid this fragility entirely.
  • A backreference (\1) matches literal repeated text, not "the same pattern again" — a common misunderstanding when trying to match balanced or repeated structures.
  • Optional groups that don't participate in a match (e.g. inside an unmatched alternative) return undefined/null in most languages, which needs explicit handling before use.

Related terms

  • Regex — the broader pattern language capture groups are a feature of.
  • Lookahead — a related but distinct construct: it checks context without capturing or consuming any text.

See also

  • Tool: Regex Tester — test patterns with live capture-group highlighting to see exactly what each group matches.