W3docs

Python string.replace regular expression

You can use the re module in Python to use regular expressions with the replace() method.

Python's built-in str.replace() method does not support regular expressions. To replace text using a regex pattern, you must use the re.sub() function from the re module. Here's an example:

Using re.sub() with regular expressions in Python

import re

string = "The quick brown fox jumps over the lazy dog."

# Replace all occurrences of "the" with "a" using a regular expression
new_string = re.sub("the", "a", string)
print(new_string)

This will output: "The quick brown fox jumps over a lazy dog."

Note that re.sub() is case-sensitive by default, so "The" remains unchanged. To match both cases, pass the re.IGNORECASE flag: re.sub("the", "a", string, flags=re.IGNORECASE).

You can also use a regular expression to match and replace a specific pattern in a string. Here's an example:

Matching and replacing patterns with regex in Python

import re

string = "The quick brown fox jumps over the lazy dog."

# Replace all occurrences of the word that starts with "t" or "T" and ends with "e" with "a" 
new_string = re.sub(r"\b[tT]\w*e\b", "a", string)
print(new_string)

This will output: "a quick brown fox jumps over a lazy dog."

Note that the re.sub() function takes three arguments: the regular expression pattern, the replacement string, and the original string.