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.

PRE REQUISITE:
Creating a regex object:

https://cppsecrets.com/users/164811151141051079711011610410995105115495746114118105116109641141181011054610110011746105110/Python-re-compile.php



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


CODE:

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 = regex_object.search(s) # contains result of the search
print("The number detected in the example string is "+search_answer.group()+".")




OUTPUT:

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.

Comments