Regex capture group
A capture group is a part of a regular expression wrapped in parentheses that both groups its contents and remembers the text it matched, so you can extract it, reuse it later in the pattern with a backreference, or refer to it in a replacement.
The basics
Parentheses create a numbered group. Groups are numbered by the position of their opening parenthesis, left to right, and group 0 is always the whole match.
Pattern: (\d{4})-(\d{2})-(\d{2}) applied to 2026-09-18:
| Group | Text |
|---|---|
| 0 | 2026-09-18 |
| 1 | 2026 |
| 2 | 09 |
| 3 | 18 |
Variations
- Non-capturing group:
(?:...)groups without remembering. Use it when you only need grouping for a quantifier or alternation, such as(?:cat|dog)s?. - Named group:
(?<year>\d{4})gives the group a name, so you readmatch.groups.yearinstead of counting positions. Named groups are part of modern JavaScript, and syntax varies between regex flavors. - Backreference:
\1matches the same text group 1 matched. The pattern(\w+) \1finds a repeated word such as “the the”. - In a replacement: JavaScript uses
$1, or$<year>for a named group. Swapping a date’s order looks like'2026-09-18'.replace(/(\d{4})-(\d{2})-(\d{2})/, '$3/$2/$1'), which gives18/09/2026.
Common pitfalls
- A repeated group keeps only its last match. Applying
(a|b)+toabableaves group 1 asb, not all four letters. To capture the whole run, wrap the repetition:((?:a|b)+). - An optional group that did not take part is
undefined, not an empty string, in JavaScript. Check before using it. - Miscounting nested groups. In
((a)(b)), group 1 is the outer one, group 2 isaand group 3 isb. - Greedy versus lazy.
(.*)grabs as much as it can. Use(.*?)to stop at the first opportunity. - Catastrophic backtracking. Nested quantifiers like
(a+)+$can take exponential time on a non-matching input, which can freeze a page or a server. Keep groups with quantifiers simple, and test patterns on hostile input. - Flavor differences. Lookbehind support, named-group syntax and Unicode handling all differ between JavaScript, Python, PCRE and others. Test in the flavor you deploy.
Related terms
- JSON (JavaScript Object Notation) — JSON is a lightweight, language-independent text format for structured data made of objects, arrays, strings, numbers, booleans and null. It is specified by RFC 8259 and ECMA-404 and is the default data format of web APIs.
References
Ads on this page
Non-personalized ads help keep Vaultools free — Google decides where they appear on the page.
Go Pro to remove them →