Search and replace with groups

Regular expressions · Practical · 12 min

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>0 when a digit follows, since \10 would mean group 10.
  • JavaScript replace/replaceAll: $1, $<name>, $& for the whole match, $$ for a literal dollar.
  • sed: \1 and &; 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.subn also returns how many were made.
  • In JavaScript, replace with a string pattern or a regex without g replaces only the first match; use the g flag or replaceAll.
  • 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.

Check yourself

  1. What does 'a-b'.replace(/(\w)-(\w)/, '$2-$1') return in JavaScript?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: docs.python.org/3/library/re.html#re.sub

Builds on

Unlocks

Nothing builds on this yet.