Learn regular expressions · Lesson 8
Captures and backreferences
Parentheses capture: besides grouping, they remember the part of the match inside them, so your code can take it out. The date 2026-10-24 matched by (\d{4})-(\d{2})-(\d{2}) gives the whole match and three groups: 2026, 10 and 24.
/(\d{4})-(\d{2})-(\d{2})/g2 matchesFrom 2026-10-24 to 2026-11-02.Try it in Dotstar →
Try it in Dotstar and the Matches tab shows each group, coloured in the text.
Numbered from the left
Groups are numbered by their opening parenthesis, counting from the left, from 1; group 0 is the whole match. Nested groups count too: in ((\d{4})-(\d{2})), group 1 is the year and month together, 2 the year, 3 the month. (?:…) groups don’t count, which is why they’re worth using when you don’t need the text.
Named groups
Numbers get hard to follow, and shift when the pattern changes. A named group says what it is: (?<year>\d{4}), and the code asks for year.
/(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/g2 matchesFrom 2026-10-24 to 2026-11-02.Try it in Dotstar →
A group in a repetition
A group that repeats keeps only what it matched the last time round. (\w)+ on abc matches all three letters, but group 1 is c. To have every round, capture around the repetition instead, (\w+), or match repeatedly in code.
Backreferences: the same text again
\1 in a pattern matches the text group 1 matched, exactly, there and then. So \b(\w+) \1\b finds a word written twice:
/\b(\w+) \1\b/gi2 matchesthe the cat sat sat on the matTry it in Dotstar →
The backreference matches the same text, not the same pattern: (\d)\1 is a digit and the same digit again, 11 or 77, not 12. A named group is referred to with \k<name>.