How do named capture groups work in Python and JavaScript?
Quick answer
A named capture wraps the part you want to keep and assigns it a readable name. For the same label-and-value pattern, Python writes (?P<label>...) and reads named captures with groupdict(); JavaScript writes (?<label>...) and reads them from match.groups.label. The capture syntax differs, so use the version for your language.
The question, the details, the next step.
A practical checklist
Write the capture names you need, such as
labelandvalue.Use Python’s
(?P<name>...)syntax or JavaScript’s(?<name>...)syntax.Choose group contents that fit the actual separator and allowed text.
Check that a match exists before reading its captured fields.
Verify the output with an example containing the expected label and value.
A few more useful answers
Can I use the same named-group spelling in both languages?
No. Python uses (?P<name>...), while JavaScript uses (?<name>...). The capture names can be the same, but the syntax must match.
What does `groupdict()` give me in Python?
It gives you a dictionary of the named captures on the match object, so you can retrieve a value by its name, such as fields["label"]. [S1]
Where are named captures stored in a JavaScript `exec()` result?
Read them from the result’s groups property, for example match.groups.label. Check that match is not null before reading that property. [S2]
Sources
References used for this guide.
- [S1] Python 3.15 re — Regular expression operations docs.python.org · Checked
- [S2] MDN: JavaScript named capturing group `(?<name>...)` developer.mozilla.org · Checked
