Python re compile

Python re compile

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.


import re regex_object = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d') # \d represents a digit(0-9) s = "He is the president and his number is 415-555-4242 , so leave a message." # example string search_answer = # contains result of the search
print("The number detected in the example string is "".")


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.