Regex & Text

Regex Groups, Capture Groups and Backreferences

Parentheses can group part of a pattern and, by default, capture the text it matched. Backreferences match the same text captured earlier.

Published

What parentheses do in regex

Grouping changes precedence and quantifier scope. A capturing group also stores its matched substring.

Capturing groups

The full match and capture are separate results; numbered captures begin with group 1.

(foo|bar)

Non-capturing groups

Use this form when structure is needed but no captured value is required.

(?:foo|bar)+

Backreferences

\1 matches the exact text captured by the first group, which can find adjacent repeated words.

\b(\w+)\s+\1\b

Named capture groups

Modern JavaScript exposes named captures through the groups result object.

(?<code>[A-Z]{2})-(?<id>\d{4})

Nested and optional groups

Numbering follows the order of opening capturing parentheses. A group that does not participate in a match can be undefined even when the overall pattern matches.

Common mistakes

  • Using the wrong group number after editing a pattern.
  • Capturing when only grouping is required.
  • Forgetting an extra backslash in string or JSON source.
  • Confusing a capture with the complete match.

Try capture groups in Regex Tester

Run the examples to inspect the tool's actual match and group output.

Try the example

Inspect numbered capture groups

The first group captures a two-letter prefix and the second captures four digits.

([A-Z]{2})-(\d{4})

Expected result: Matches AB-1234 and XY-9876 with two captures each.

Try the example

Find repeated words with a backreference

The backreference requires the second word to equal the first capture.

\b(\w+)\s+\1\b

Expected result: Matches go go and now now, but not stop now.

Inspect real captures

Test groups and backreferences

See full matches and captured groups in Regex Tester.

Open in Regex Tester →