Refer to captured groups in your replacement string
Substitution (re.sub, sed s/old/new/, str.replace_all with regex) lets you reference captured groups in the replacement.
- Python re.sub:
\1,\2, or\g<name>for named groups - JavaScript replace:
$1,$2, or$<name> - sed:
\1,\2 - ripgrep --replace:
$1,$2or$name
The classic use: format conversion
Convert 2026-05-04 to 05/04/2026: re.sub(r'(\d{4})-(\d{2})-(\d{2})', r'\2/\3/\1', text).
The capture groups are reordered in the replacement. This is how regex earns its keep in code mods, log reformatting, CSV-to-CSV transformation.
The 'whole match' reference
Group 0 is the entire match. Useful for wrapping: re.sub(r'\d+', r'[\g<0>]', text) wraps every number in brackets without you having to capture it explicitly. JavaScript: $&; sed: &.
Function as replacement
For complex replacements, most languages let you pass a function instead of a string. Python: re.sub(pattern, callable, text). The callable receives a Match object and returns a string. This unlocks dynamic logic — uppercasing, lookups, conditional rewrites — that pure replacement strings can't express.