Python (Scripting) - Replace pattern using re.sub
by
Jeremy Canfield |
Updated: April 01 2024
| Python (Scripting) articles
There are two similar modules that can be used to replace a pattern.
- replace (non regular expression)
- re.sub (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, flags=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)
Did you find this article helpful?
If so, consider buying me a coffee over at