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



Comments


Add a Comment


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