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.
The question, the details, the next step.
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>withre.sub.Use JavaScript replacement references such as
$1withString.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?
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.
- [S1] Python 3.15.2 re — Regular expression operations docs.python.org · Checked
- [S2] JavaScript String.prototype.replace() developer.mozilla.org · Checked
