Groups and CapturingLesson 2.2
Named capture groups in regex for readable patterns
named group syntax, groups.name access, named backreferences, Python named groups, readability benefits
Name Your Groups Instead of Counting Them
Numbered groups break when you add or remove a group. Named groups solve this: use (?<name>pattern) in JavaScript (ES2018+) and (?P<name>pattern) in Python.
// JavaScript
const re = /^(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})$/;
const { groups } = '2024-06-15'.match(re);
console.log(groups.year); // '2024'
console.log(groups.month); // '06'
console.log(groups.day); // '15'
Named Groups in Replacements
// JavaScript — use $<name> in replacement string
'2024-06-15'.replace(re, '$<month>/$<day>/$<year>')
// => '06/15/2024'
Named groups are worth the extra syntax on any pattern you will maintain.
