Recent chats
ASKGEEZ Q&A GUIDETechnology & devices

How do replacement groups preserve parts of matched text?

Quick answer

Put parentheses around each part you want to reuse; these are capturing groups. In a Python re.sub replacement string, refer to groups with \g<1> and \g<2>. In JavaScript String.prototype.replace, use $1 and $2. For example, capturing Maria and Cruz separately lets you swap them to produce Cruz, Maria. The reference syntax depends on the language.

LET’S WORK THROUGH IT

The question, the details, the next step.

Question

I have text with two parts, like a first name followed by a last name. How do I keep both matched parts so I can put them in the opposite order?

Geez

Use capturing groups: parentheses in the pattern mark the text you want to reuse. For the example Maria Cruz, the pattern r'(\w+) (\w+)' has two groups. Group 1 captures Maria, and group 2 captures Cruz.

In Python’s re.sub, write references to those groups in the replacement string. To put the second captured part first, followed by a comma and the first part, use r'\g<2>, \g<1>'. Python documents this form for inserting captured text into a replacement; using \g<2> also avoids ambiguity if a digit follows a group reference. [S1]

Here is the complete example:

import re

text = "Maria Cruz"
result = re.sub(r'(\w+) (\w+)', r'\g<2>, \g<1>', text)
print(result)

Output:

Cruz, Maria

The r prefixes make these raw Python strings, so the backslashes in the pattern and replacement are easier to read as regex syntax. [S1]

Follow-up question

I’m doing the same thing in JavaScript. Can I copy the Python replacement string, or does JavaScript refer to the groups differently?

Geez

JavaScript uses a different replacement-string convention. With a regular expression passed to String.prototype.replace, numbered groups are inserted with $1, $2, and so on—not Python’s backslash forms. [S2]

The equivalent JavaScript example is:

const text = "Maria Cruz";
const result = text.replace(/(\w+)\s(\w+)/, "$2, $1");
console.log(result);

Output:

Cruz, Maria

The parentheses still capture the first and second pieces; only the replacement references change. Here $2 inserts the second capture and $1 inserts the first. The JavaScript example uses \s between the groups to match whitespace. [S2]

When moving a regex substitution between these languages, check both the pattern and the replacement syntax rather than copying the replacement string unchanged.

Follow-up question

How do I work out which group number goes where, and what should I check before using the pattern on more text?

Geez

Number capturing groups by the order of their opening parentheses: the first capturing pair is group 1, the next is group 2. Write down what each group is meant to hold before arranging the replacement.

For this pattern, the mapping is:

  1. \w+ before the space: first part (Maria)
  2. \w+ after the space: second part (Cruz)

The replacement lists the desired output order. \g<2>, \g<1> in Python, or $2, $1 in JavaScript, means “second part, comma, first part.” Try it on a representative input and inspect the output before applying it to more text.

This example is limited to two word-like parts separated by whitespace. It does not establish that this pattern fits every naming format, punctuation style, or input. Adjust it for the text you need to process.

Follow-up question

Can you give me a compact template I can reuse when I need to swap two captured fields?

Geez

Keep the pattern’s captures in the order the fields appear, then refer to them in reverse order in the replacement. For two fields separated by a space, the pattern and replacement pair is:

Python:

r'(\w+) (\w+)'       # pattern
r'\g<2>, \g<1>'     # replacement

JavaScript:

/(\w+)\s(\w+)/       // pattern
"$2, $1"             // replacement

For Maria Cruz, both produce Cruz, Maria. The separator and field patterns here suit this simple example; change them if your input uses a different format. Check the group order against one sample so the replacement puts each field where you intend.

A practical checklist

  • Put parentheses around each text part you need to reuse.

  • Number the groups in order and note what each one captures.

  • Use Python replacement references such as \g<1> with re.sub.

  • Use JavaScript replacement references such as $1 with String.prototype.replace.

  • Check the pattern and output on a representative input before applying it more widely.

A few more useful answers

Can I use Python’s `\g<2>` notation in a JavaScript replacement string?

No. For regex replacements with JavaScript String.prototype.replace, use $2 for the second numbered capture. Python re.sub replacement strings use forms such as \g<2>. [S1] [S2]

Does this example replace every matching part of a JavaScript string?

Not as written: the example uses a regex without the g flag, so JavaScript replace() replaces only the first match. The g flag makes it replace every match. [S2]

Will the two-word pattern work for every kind of name or field?

Not necessarily. The example demonstrates how captures can be rearranged, but does not establish that the pattern suits every input format. Test and adjust it for the text you need to process.

Sources

References used for this guide.

  1. [S1] Python 3.15.2 re — Regular expression operations
    docs.python.org · Checked
  2. [S2] JavaScript String.prototype.replace()
    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