Bulk edits, data cleaning and format conversion are all search-and-replace with groups.
Every regex API has a substitute operation, and the replacement string can refer to captured groups. The syntax differs:
- Python
re.sub:\1,\g<1>or\g<name>. Use\g<1>0when a digit follows, since\10would mean group 10. - JavaScript
replace/replaceAll:$1,$<name>,$&for the whole match,$$for a literal dollar. - sed:
\1and&; editors such as VS Code use$1.
Instead of a template you can pass a function that receives the match and returns the replacement. Use it when the new text has to be computed: converting units, changing case, looking values up in a dict.
Other useful knobs:
- Python
re.sub(p, r, s, count=1)limits the number of replacements;re.subnalso returns how many were made. - In JavaScript,
replacewith a string pattern or a regex withoutgreplaces only the first match; use thegflag orreplaceAll. - Escape backslashes in replacement templates; if the replacement comes from user data, use a function returning it so no template syntax is interpreted.
Example
import re
dates = "due 2026-10-17, paid 2026-09-30"
print(re.sub(r"(\d{4})-(\d{2})-(\d{2})", r"\3/\2/\1", dates))
# due 17/10/2026, paid 30/09/2026
print(re.sub(r"(?P<key>\w+)=(?P<val>\w+)", r"\g<val>=\g<key>", "a=1 b=2")) # 1=a 2=b
prices = "apple 1.50 USD, pear 0.75 USD"
to_eur = lambda m: f"{float(m[1]) * 0.86:.2f} EUR"
print(re.sub(r"(\d+\.\d+) USD", to_eur, prices))
# apple 1.29 EUR, pear 0.65 EUR
print(re.subn(r"\s+", " ", "too many spaces")) # ('too many spaces', 2)
# JavaScript equivalent:
# "2026-10-17".replace(/(\d+)-(\d+)-(\d+)/, "$3/$2/$1") // "17/10/2026"Remember
- Python templates use \1 or \g<name>; JavaScript uses $1 or $<name>
- Pass a function when the replacement must be computed
- JavaScript replace changes only the first match unless you use g or replaceAll
Watch out for
- Writing \10 in Python meaning group 1 followed by 0; write \g<1>0.