Skip to main content

regex.replace

The regex.replace function replaces every match of a regular expression with a fixed string. Use it to normalize names, strip unwanted characters, and clean up text from commands and files.

Usage​

regex.replace(pattern, replacement, text)

Arguments​

pattern

Required. The regular expression, as a string, in RE2 syntax. Inline flags such as (?i) and (?m) work. Lookahead, lookbehind, and backreferences in the pattern are not available.

replacement

Required. The text that replaces each match. It is used exactly as written: a $1 or ${name} in the replacement stays in the result as those characters, and backslashes and dollar signs need no escaping. Use an empty string to delete matches.

text
Required. The string to rewrite.

All three arguments are required and can be passed positionally or by keyword.

Returns​

A new string with every match replaced. When nothing matches, the result equals text.

Examples​

Normalize a name​

print(regex.replace("-+", "_", "us-east--1"))
us_east_1

Collapse whitespace​

print(regex.replace("\\s+", " ", "a b \t c"))
a b c

Delete matches​

print(regex.replace("a", "", "banana"))
bnn

Replacement text is literal​

Capture groups cannot be referenced from the replacement. Text such as $2-$1 is inserted as it is:

print(regex.replace("(\\w+)-(\\d)", "$2-$1", "us-1"))
$2-$1

Build a slug​

def slug(value):
return regex.replace("[^a-z0-9]+", "-", value.lower())

output = slug("Prod US East")
prod-us-east

Errors​

  • A pattern that is not valid RE2 fails with invalid regex: ... followed by the reason.
  • A missing argument, or an argument that is not a string, fails with an argument error.