Python re search

Python re search

This is my second article on methods to use the re Python library and will entail the exemplification and a brief summary of the usage of the .search() method.

Creating a regex object:

Let us now bring back the example we considered in my first article that covered the usage of the .compile() method.


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 variable search_answer holds all the matched objects, in this case "415-555-4242" is the only substring that matches the regular expression in the variable regex_object holds which can be found by using the .search() method with the string to be searched as the argument.