Recent chats
ASKGEEZ Q&A GUIDETechnology & devices

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.

LET’S WORK THROUGH IT

The question, the details, the next step.

Question

I have a string like status: ready and want to capture status as the label and ready as the value. How do I name those parts?

Geez

Use one named group for each part you want to retrieve. Here the pattern stops the label at the colon, allows optional whitespace after it, and captures the remaining text as the value.

Python:

import re

text = "status: ready"
pattern = r"(?P<label>[^:]+):\s*(?P<value>.+)"
match = re.search(pattern, text)

JavaScript:

const text = "status: ready";
const pattern = /(?<label>[^:]+):\s*(?<value>.+)/;
const match = pattern.exec(text);

The parts inside each named group are the captured text. Python names a group with (?P<name>...); JavaScript uses (?<name>...) instead. [S1] [S2]

Follow-up question

How do I get the two captured values out of each match?

Geez

In Python, first check that a match was found, then call groupdict() to get a dictionary of named captures. Python’s match object also provides group-access methods for named captures. [S1]

if match:
    fields = match.groupdict()
    print(fields["label"])  # status
    print(fields["value"])  # ready

In JavaScript, check the result of exec() before reading its groups property. The named values are available through that property, for example match.groups.label and match.groups.value. [S2]

if (match) {
  console.log(match.groups.label); // status
  console.log(match.groups.value); // ready
}

Both examples display the same two strings. The result containers differ: a Python dictionary from groupdict() versus the JavaScript match result’s groups object. Keep the match check in place so code does not try to read captures when there is no match.

Follow-up question

Can you show the complete equivalent examples together so I can adapt one?

Geez

Here are complete versions you can copy and then modify. They print the captured fields as a small, readable output.

Python:

import re

text = "status: ready"
match = re.search(r"(?P<label>[^:]+):\s*(?P<value>.+)", text)

if match:
    fields = match.groupdict()
    print(f"label={fields['label']}")
    print(f"value={fields['value']}")

JavaScript:

const text = "status: ready";
const match = /(?<label>[^:]+):\s*(?<value>.+)/.exec(text);

if (match) {
  console.log(`label=${match.groups.label}`);
  console.log(`value=${match.groups.value}`);
}

For this input, both display:

label=status
value=ready

To adapt the pattern, change the text each group is meant to accept, not the retrieval step. For example, [^:]+ means “one or more characters other than a colon”; .+ captures one or more characters after the optional whitespace. This simple pattern is for a single-line label followed by a colon and a nonempty value. It is not a general parser for every possible label-and-value format.

Follow-up question

What should I check if one version works but the other does not?

Geez

Check the language-specific group spelling first: Python uses (?P<label>...), while JavaScript uses (?<label>...). Then check how you retrieve the result: use match.groupdict() in Python and match.groups.label in JavaScript. Finally, confirm a match was actually found before accessing its captures.

The pattern shown assumes a colon-separated label and value and a nonempty value. If your input has a different separator, can include colons in a value, or may omit either part, decide how those cases should behave before changing the expression. JavaScript’s named-group documentation notes that a named property for a group not matched in an alternative has the value undefined; the examples here use no alternatives and do not address every edge case. [S2] If the input format is more complex, test representative examples rather than assuming this small pattern covers it.

A practical checklist

  • Write the capture names you need, such as label and value.

  • 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.

  1. [S1] Python 3.15 re — Regular expression operations
    docs.python.org · Checked
  2. [S2] MDN: JavaScript named capturing group `(?<name>...)`
    developer.mozilla.org · Checked

YOUR QUESTION. YOUR DETAILS.

Let’s work through your situation.

Get a tailored answer or help with your next task. Starts at $1, with a quote before you pay.

Ask your own question
← Back to Geez at Work