Python (Scripting) - Replace pattern using re.sub

by
Jeremy Canfield |
Updated: August 25 2024
| Python (Scripting) articles
There are two similar modules that can be used to replace a pattern.
- replace (non regular expression)
- re.sub (substitute, regular expression - this article)
In this example, Hello is replaced with Goodbye.
#!/usr/bin/python
import re
foo = "Hello World"
bar = re.sub("Hello", "Goodbye", foo)
And here is an example of how to do a replacement with re.sub where everything before the matching text Hello is replaced with nothing.
#!/usr/bin/python
import re
foo = "Hello World"
foo = re.sub(".*Hello ", "", foo)
print(foo)
And here is how to ignore case.
#!/usr/bin/python
import re
foo = "Hello World"
foo = re.sub(".*hello ", "", foo, re.IGNORECASE)
print(foo)
Here is how to evaluate two (or more) expressions. This is an or clause, where the expression will evaluate to true if the foo variable contains Hello or World.
#!/usr/bin/python
import re
foo = "Hello World"
bar = re.sub('.*(Hello|World).*', '', foo, re.IGNORECASE)
Since re.sub contains parenthesis () if you want to substitute parenthesis you'll need to escape the parenthesis. Almost always, you'll want to use r (raw) in the escape pattern.
#!/usr/bin/python
foo = "Hello (World)"
foo = re.sub(r'\(', '', foo)
foo = re.sub(r'\)', '', foo)
Did you find this article helpful?
If so, consider buying me a coffee over at