Named Capture Groups — (?<name>...) for Self-Documenting Regex

Use named capture groups (?<name>...) to make regex self-documenting and easier to maintain. Includes JavaScript access patterns and replacement examples.

Advanced Techniques

Detailed Explanation

Named Capture Groups

Named capture groups make regular expressions self-documenting and decouple your code from the order of groups in the pattern. They were standardized for JavaScript in ES2018.

Syntax

(?<name>pattern)

Example: Date Parsing

const m = "2024-06-15".match(/(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/);
m.groups.year   // "2024"
m.groups.month  // "06"
m.groups.day    // "15"

Use in Replacements

Reference named groups with $<name>:

"2024-06-15".replace(
  /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/,
  "$<month>/$<day>/$<year>"
)
// "06/15/2024"

Backreferences

\k<name> references a named group within the pattern itself:

/(?<word>\w+)\s+\k<word>/.test("hello hello")  // true

Useful for finding repeated words or matching paired delimiters.

Tested Examples

Pattern Input groups
(?<area>\d{3})-(?<num>\d{4}) "555-1234" area=555, num=1234
(?<name>\w+)\s+\k<name> "go go" name=go
(?<proto>https?):\/\/(?<host>[^/]+) "https://x.io/path" proto=https, host=x.io
#(?<hex>[a-f0-9]{6}) "#ff8800" hex=ff8800

Why Named Groups Improve Code

Without names:

const [, year, month, day] = m;

With names:

const { year, month, day } = m.groups;

When the pattern evolves (a new group is inserted), positional code breaks; named-group code keeps working.

Restrictions on Names

  • Names must be valid JavaScript identifiers
  • Each name must be unique within the pattern
  • ASCII letters, digits, underscores, and dollar signs are allowed; names cannot start with a digit

Mixing Named and Numbered Groups

Both work together. (?<key>k)(v) exposes groups.key and m[2] for the unnamed group.

Practical Recommendation

Use named groups whenever a pattern has more than two captures, or when the captures are ambiguous ((\d+)/(\d+)/(\d+) could be MM/DD/YYYY or DD/MM/YYYY). Self-documentation pays for itself the first time you revisit the regex six months later.

Use Case

Parsing log lines into named fields for structured logging, extracting components from URLs without depending on positional indices, or making complex date parsing patterns maintainable across team handovers.

Try It — Regex Cheat Sheet

Open full tool