Skip to main content
Regexflux
Lesson 9 of 120 completed

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})/g

Parses an ISO date with named year, month, and day groups

Date: 2024-03-17
event on 1999-12-31
2024/03/17
17-03-2024
/(?<first>\w+)\s+(?<last>\w+)/g

Captures a first and last name as named groups

John Smith
Jane Doe
Alice
Bob Jones

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:

Must match

Server: 192.168.1.1
IP address 10.0.0.1 is blocked
Connect to 127.0.0.1:8080
Gateway: 172.16.0.1

Must not match

192.168.1
not an ip address
hostname:8080
256.1.1.1.1