Named Capture Groups
Give capture groups descriptive names to make complex patterns readable and maintainable.· 7 min
Concept
Named capture groups use the syntax (?<name>...) to attach a label to each captured value. This is far more readable than numbered groups when a pattern has many captures.
In JavaScript, named group values are available on the groups property of a match result:
``js
const m = '2024-03-17'.match(/(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/);
console.log(m.groups.year); // '2024'
Naming rules: group names must start with a letter or underscore, and contain only letters, digits, and underscores. You can also use the Python-style syntax (?P<name>...) for cross-language compatibility.
/(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/gParses an ISO date with named year, month, and day groups
/(?<first>\w+)\s+(?<last>\w+)/gCaptures a first and last name as named groups
Exercise
Write a pattern with named groups to match an IPv4 address like "192.168.1.1". Capture each of the four octets.
Your pattern: