Script Valley
Regex: Actually Useful Patterns
Groups and CapturingLesson 2.1

How capturing groups work in regex

capturing group syntax, group index, match array, nested groups, group numbering order

Groups Let You Extract Sub-Matches

Capturing groups

Parentheses do two things: they group part of a pattern (so quantifiers apply to the whole group), and they capture the matched text into a numbered slot you can access after the match.

const m = '2024-06-15'.match(/^(\d{4})-(\d{2})-(\d{2})$/);
// m[0] => '2024-06-15'  — full match
// m[1] => '2024'        — group 1
// m[2] => '06'          — group 2
// m[3] => '15'          — group 3

Group Numbering

Groups are numbered left to right by their opening parenthesis. Nested groups count too — the outer group gets a lower index than the inner group it contains.

const m = 'abc'.match(/(a(b)c)/);
// m[1] => 'abc'  — outer group
// m[2] => 'b'    — inner group

Using Groups With replace()

In replacements, $1, $2, etc. refer back to captured groups. This is how you reformat data without writing a parser.

'2024-06-15'.replace(/^(\d{4})-(\d{2})-(\d{2})$/, '$2/$3/$1')
// => '06/15/2024'

Groups are one of the highest-leverage features in regex. Once you have the groups, the hard work of extraction is done.

Up next

Named capture groups in regex for readable patterns

Sign in to track progress