Learn regular expressions · Lesson 9

Replacing

A regex replace finds the matches and puts a replacement in place of each. The replacement can be plain text, but its power is that it can use the groups the pattern captured.

Groups in the replacement

$1 in the replacement is what group 1 matched. So a date can be turned around:

/(\d{4})-(\d{2})-(\d{2})/g→$3/$2/$12 matches
From 2026-10-24 to 2026-11-02.
Replaced
From 24/10/2026 to 02/11/2026.
Try it in Dotstar →

$& is the whole match, so [$&] puts brackets around each one, and a named group is $<name>:

/(?<user>\w+)@(?<host>[\w.]+)/g→$<host>: $<user>2 matches
alice@example.com, bob@mail.example.org
Replaced
example.com: alice, mail.example.org: bob
Try it in Dotstar →

The first or every one

Without the g flag JavaScript replaces only the first match; with it, every one. Other languages usually choose first or all through the API rather than a flag: Java has replaceFirst and replaceAll, Ruby sub and gsub, while Python’s re.sub replaces all unless given a count, re.sub(pattern, repl, text, count=1).

/o/→01 match
foo boo
Replaced
f0o boo
Try it in Dotstar →

A dollar that means a dollar

Since $ introduces a group, a plain dollar sign in the replacement is written $$: $$& is the text “$&”, and $$1 is “$1”. The pattern has its own escaping (a dollar there is \$); the replacement has this one.

/(\w+)@/g→$1xin each engine
alice@,bob@
Go, Rust,
JavaScript, PCRE2, .NET, Javaalicex,bobx

Run in each engine itself, as Dotstar’s Compare runs them, when this page was checked.

When text isn’t enough

Some replacements can’t be written as text: upper-casing a group, adding one to a number, looking something up. For those, many languages’ APIs accept a function instead of a replacement string, called once per match. What it receives varies: JavaScript passes the match and its groups, text.replace(re, (m, a, b) => …); Python and .NET a match object, re.sub(pattern, lambda m: …, text) and Regex.Replace with a MatchEvaluator; Go’s ReplaceAllStringFunc only the whole match.