Named capture groups

Beginner · 8 min

Label a group with (?<name>...) or Python's (?P<name>...) and read it by name. Covers groups objects, $<name>, \k<name> and duplicate names.

Before thisCapturing groups and numberingNon-capturing groups

dcode · 8 min

Named capture groups

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by dcodeReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A named group, (?<year>\d{4}) in JavaScript, still gets its number, and you can also read it by name from m.groups.year.
  • JavaScript puts named groups on m.groups, an object with no prototype. It is undefined when the pattern has no named groups, and a group that did not take part is a key whose value is undefined.
  • Python spells it (?P<name>...) and reads it with m.group('name'), m['name'] or m.groupdict(). Python 3.9 rejects the (?<name>...) spelling with an error.
  • In replacements, JavaScript uses $<name> and Python uses \g<name>. In the pattern itself, JavaScript uses \k<name> and Python uses (?P=name).
  • Reusing one name twice in a pattern is a SyntaxError in JavaScript unless the two groups sit in different alternatives. Python 3.9 and PCRE both refuse it, and Perl allows it.

Numbers are fine until the pattern changes

Numbered groups work well for a three-group date pattern. They stop working when the pattern is long, or when someone else edits it. A log pattern with nine groups, where field six is the status code, is m[6] in your code. A colleague adds a group near the start, and m[6] is now the wrong field, with no error. Nothing fails. Wrong data flows downstream.

The fix is the same one programming languages found long ago. Don’t refer to things by position. Give them names.

The syntax

A named capture group puts a name after (?< in JavaScript, Perl and PCRE:

const re = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;
const m = re.exec('released 2026-11-23 today');
m.groups
// [Object: null prototype] { year: '2026', month: '11', day: '23' }
m.groups.year  // '2026'
m[1]           // '2026'
const { year, month, day } = m.groups;

The group keeps its number too. m[1] is still the year. Naming adds a second way to reach it; it doesn’t remove the first. The groups object has a null prototype (I checked with Object.getPrototypeOf(m.groups)), so a name like constructor can’t collide with something inherited. A name can’t start with a digit: (?<1a>x) threw SyntaxError: Invalid capture group name.

Two behaviours worth knowing. If the pattern has no named groups at all, m.groups is undefined, not an empty object. And if a named group didn’t take part in the match, its key is still there with the value undefined:

/(?<a>x)|(?<b>y)/.exec('y').groups
// { a: undefined, b: 'y' }

The same dict-with-gaps shape appears in Python as {'a': None, 'b': 'y'}.

Using names in the rest of the pattern and in replacements

A name works anywhere you would use a number. In a replacement string, JavaScript has $<name>:

'2026-11-23'.replace(re, '$<day>/$<month>/$<year>')  // '23/11/2026'

If you pass a function as the replacement, JavaScript hands it the groups object as its last argument, so (...args) => { const g = args.at(-1); ... } gave '23.11.2026'. In the pattern, a named backreference \k<q> repeats whatever group q matched. /(?<q>["']).*?\k<q>/ found "hi" in say "hi" and 'bye', picking the opening quote’s twin. The backreferences lesson goes further.

Python’s spelling

Python uses (?P<name>...), with a P. I ran Python 3.9.6:

>>> m = re.search(r'(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})', 'released 2026-11-23 today')
>>> m.group('year'), m.group(1), m['month']
('2026', '2026', '11')
>>> m.groupdict()
{'year': '2026', 'month': '11', 'day': '23'}
>>> re.sub(r'(?P<y>\d{4})-(?P<m>\d{2})-(?P<d>\d{2})', r'\g<d>/\g<m>/\g<y>', '2026-11-23')
'23/11/2026'

The backreference inside a pattern is (?P=name). And the JavaScript spelling fails:

re.error: unknown extension ?<y at position 1 | (?<year>\d{4})

Perl accepted (?<year>...) and put the result in the %+ hash ($+{year}). pcre2grep accepted both (?<year>...) and (?P<year>...). I only ran Python 3.9, so I can’t say what a newer Python does with the angle-bracket form.

Duplicate names

What if two groups share a name? That is a bug in most patterns, and I got a different error from each tool:

JavaScript:   SyntaxError: Duplicate capture group name
Python 3.9:   re.error: redefinition of group name 'a' as group 2
pcre2grep:    two named subpatterns have the same name (PCRE2_DUPNAMES not set)

But there’s one case where a repeated name is useful: alternatives that capture the same thing in different shapes. /(?<y>\d{4})-\d\d|\d\d-(?<y>\d{4})/ accepts either 2026-11 or 11-2026 and puts the year in groups.y in both cases. Node 26 accepted it and returned 2026 for both inputs. Perl 5.34 accepted it too. Python 3.9 rejected the equivalent (?P<y>...) version, and pcre2grep rejected it until I turned on (?J), its “allow duplicate names” option. So duplicate names are legal when only one can match at a time and when the engine is new enough. Don’t write them in portable code.

About the video

The embedded video is dcode’s “EASILY The BEST Way To Do REGEX in JavaScript”, published 21 November 2023 and 7 minutes 37 seconds long. Its chapters are an introduction to named groups, standard capture groups, implementing named groups, destructuring named groups and handling potential errors. The description says it shows how to use named capturing groups to extract text from matches, and links MDN. That fits this lesson’s JavaScript half closely. It is JavaScript only, so the Python and duplicate-name material above is not in it, and I couldn’t read a transcript to see how it handles the unmatched-group case. English per its title and description.

What I did not run

Python 3.11 and later, .NET and Java, and regex101’s display of named groups.

Next

Names let you refer to a group from outside. Backreferences lets the pattern refer to its own earlier captures.

Check yourself

  1. 01Why are named groups safer than numbered ones when a pattern grows?

    Adding or removing a capturing group renumbers every group after it, which silently breaks m[2] or $2 in other code. A name keeps pointing at the same group wherever it moves.

  2. 02What does m.groups hold in JavaScript when the pattern has no named groups?

    undefined, not an empty object. Code that destructures m.groups directly will throw on those patterns, so only do it when you know the pattern has names.

  3. 03How do you write the same day-month-year swap in JavaScript and in Python?

    JavaScript: '2026-11-23'.replace(re, '$<day>/$<month>/$<year>'). Python: re.sub(pattern, r'\g<day>/\g<month>/\g<year>', text). Same idea, different escape syntax.

  4. 04You paste a (?<year>\d{4}) pattern from a JavaScript answer into Python 3.9. What happens?

    re.compile raises re.error: unknown extension ?<y. Python only accepts (?P<year>...). Add the P, and for backreferences use (?P=year) in place of \k<year>.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark