Regex · <code>(...)</code>
Capturing groups
Parentheses group a subpattern and capture its text; groups are numbered by the order of their opening parenthesis.
Key facts
| Syntax | <code>(...)</code> |
|---|---|
| Numbering | By the position of the opening parenthesis, from 1 |
| Replacement | <code>$1</code> in JavaScript, <code>\1</code> in many other engines |
| Named group | <code>(?<name>...)</code> in JavaScript and PCRE |
| Python named group | <code>(?P<name>...)</code> |
| Nested groups | Outer group number is lower than inner groups |
| Access | Match array or groups object, depending on the API |
Numbering and replacements
Groups are numbered by the order in which their opening parentheses appear, not by where they close. In ((a)(b)), group 1 is the whole pair, group 2 is “a” and group 3 is “b”. A group that participates in the match but matches an empty string still has a number and an empty capture.
In JavaScript replacements, $1 inserts the first capture and $& inserts the whole match. In Python's re.sub the syntax is \1. Getting this wrong produces literal dollar signs in the output rather than an error.
Name what matters
A pattern with six numbered groups is hard to maintain because inserting one parenthesis renumbers everything after it. Named groups remove that fragility: (?<year>\d{4}) stays addressable regardless of new groups elsewhere. JavaScript exposes them in match.groups.
Named-group syntax itself is not portable — Python uses (?P<name>...) — but the concept is worth the engine-specific spelling in any pattern that will live longer than a day.
Frequently asked questions
How are capture groups numbered?
By the position of their opening parenthesis, left to right, starting at 1. Group 0 is the entire match.
What is the difference between $1 and \1?
$1 is replacement syntax in JavaScript; \1 is a backreference in the pattern or a replacement token in engines such as Python.
Do non-capturing groups take a number?
No. (?:...) groups without capturing, so it does not shift the numbering of later groups.