Bootstrap FreeKB - Python (Scripting) - Replace pattern using re.sub
Python (Scripting) - Replace pattern using re.sub

Updated:   |  Python (Scripting) articles

There are two similar modules that can be used to replace a pattern.

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 Buy Me A Coffee



Comments


Add a Comment


Please enter 3e1f06 in the box below so that we can be sure you are a human.