In this chapter let us create a few examples with Python built-in RegEx module’s methods and see what this particular module can do!
As always, you need to import the module into your python file before using it.
import re
Find whether a phrase is contained within a string or not and uses case insensitive search.
text = "Well, again, it is Hello WORLD!..." result = (re.match(".*Hello World.*", text, re.I))
Below is the return Match object.
<re.Match object; span=(0, 34), match='Well, again, it is Hello WORLD!...'>
Which shows it matches our search.
Besides using to search a string, re module also can be used to split the text into a list. The below line will split the text into a list at each white-space character.
text = "Well, again, it is Hello WORLD!..." result = re.split("\s", text) # ['Well,', 'again,', 'it', 'is', 'Hello', 'WORLD!...']
At last, let us replaced hello world with a good morning phrase.
text = "Well, again, it is Hello WORLD!..." result = re.sub("Hello WORLD", "good morning", text) # Well, again, it is good morning!...
There is still more to learn from this module which I will leave to you all to explore by yourself.