Reference · Regular expressions

re.replace

signature
re.replace(str, str, str | fn, str | null=) -> str

What it does

The text with every match of a pattern replaced. What goes in is text, where $1 to $9 stand for the groups, $<name> for a named group, $0 for the whole match and $$ for a dollar sign; or a function, called with each match (the map re.find gives) and whose result is put in as text. The flags come last: "i", "m", "s". For plain text that is not a pattern, replace is simpler.

Examples

print(re.replace("a1b22c", "\\d+", "#"))print(re.replace("2026-10-29", "(\\d+)-(\\d+)-(\\d+)", "$3/$2/$1"))print(re.replace("2026-10-29", "(?<y>\\d+)-(?<m>\\d+)-(?<d>\\d+)", "$<d>.$<m>.$<y>"))print(re.replace("hello world", "\\w+", (m) => upper(m.text)))print(re.replace("x=1, y=2", "(\\w)=(\\d)", (m) => `${m.groups[1]}=${m.groups[0]}`))
output
a#b#c29/10/202629.10.2026HELLO WORLD1=x, 2=y

Edge cases

print(re.replace("hello", "\\d+", "#"), re.replace("price 5", "\\d+", "[$0]"), re.replace("price 5", "\\d+", "$$$0"))print(re.replace("a b", " ", "$x"), re.replace("a b", " ", "$"), re.replace("ab", "a(x)?b", "[$1]"))print(re.replace("a1", "\\d", (m) => 42), re.replace("a1", "\\d", (m) => null))print(re.replace("hello", "", "-"), re.replace("abc", "x*", "-"))print(re.replace("añob", "o", (m) => str(m.start)), re.replace("Hello", "h", "J", "i"))print(re.replace("ab", "a", (m) => err("bad")))
output
hello price [5] price $5a$xb a$b []a42 anull-h-e-l-l-o- -a-b-c-añ2b Jelloerr("bad")

Errors

Replacement text that names a group the pattern does not have ($2 with one group, $<y> with no group y, $< without its >) is a runtime error, not an error value; so is a replacement that is neither text nor a function (null, a number), a pattern that is not supported, or bad flags. See re.test for what a pattern may hold.

this one fails
print(re.replace("abc", "(b)", "$2"))
output
line 1: `re.replace`: `$2`, but the pattern has 1 group
this one fails
print(re.replace("abc", "b", null))
output
line 1: `re.replace` expects what to put in (a str or a function) as argument 3, got null

Chaining

The text comes first in a pipeline, so re.replace sits between other string functions:

print("  a   b  " | trim | re.replace("\\s+", " "))print("tel: 555-1234" | re.replace("(\\d{3})-(\\d{4})", "$1 $2") | upper)print(["a1", "b22"] | map((s) => re.replace(s, "\\d+", "")))
output
a bTEL: 555 1234["a", "b"]

See also

replace, re.find, re.find_all, re.split, upper, trim

Thread
7Useful? Like it, or add to its thread below.

Thread 0 posts

On re.replace(): questions, tips, corrections, and code that uses it.

No posts yet. The first one opens the thread.

    Edit this page on GitHub · every example's output was made by running it (tools/refcheck.mjs) · questions on Discord or r/quillo