Python string.replace regular expression
You can use the re
module in Python to use regular expressions with the replace()
method. Here's an example:
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: "a quick brown fox jumps over a lazy dog."
You can also use regular expression to match and replace a pattern in the string, Here's an example:
import re
string = "The quick brown fox jumps over the lazy dog."
# Replace all occurrences of the word that starts with "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: "The 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.