The
re library is a Python library that is frequently used to cut down on redundant lines of code that are used to
match a substring with the specified pattern in the whole string.
To make use of the features of regex matching , one of the first things to be done is to create a regex object with the required pattern , which can be done using the .compile() static method*.
*static methods : methods that are used on the class and not objects belonging to the class.
Let us consider an example now.
CODE:
import re
regex_object = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')
s = "He is the president and his number is 415-555-4242 , so leave a message."
search_answer = regex_object.search(s)
print("The number detected in the example string is "+search_answer.group()+".")
The number detected in the example string is 415-555-4242.
After having created the regex object we need to look for a pattern matching the regex object's description. The number in the example string s is "415-555-4242".Which accurately matches the description of the regex object compiled in the regex_object variable.
Comments