In the last tutorial we learnt about the match function. In this tutorial we will see how the search function works. The syntax for the search function is as follows:
re.search(expression, str, flag)
The function can take three parameters the same way as in the case of match function. The first one expression refers to the regular expression that you want to match.
‘str’ is the string on which the search operation is performed to match the pattern of the string on which the search is performed.
The search function too has a flag parameter which can help in controlling the match operation.
You have already seen that the expression is nothing but a string of characters, Some characters have literal meaning and then there are some meta characters that hold special meanings. The same identifiers and modifiers are used here as well to create an expression. Mastering the art of writing expression can take time but if you look into it deeply it is very logical.
Creation of expression is same as in case of match function and you will use the same modifiers and expressions.
At this point it is important to understand the difference between the match and search function. A match function matches the expression only with the beginning however the search function will look through the entire text.
import re str_obj = re.compile("hello") match_obj = str_obj.search("A big hello to the world") if match_obj == None: print("Match not found") else: print("match found")
In the above code if you replace search by match then the output will be “Match not found”.
import re match_obj = re.search(r'bea','it is a beautiful day') if(match_obj): print("Match found") else: print("Match Not found")
In the above example we have a string “It is a beautiful day”. We have an expression : r’bea’, where we try to find if anywhere string ‘bea’ appears in the text and as expected a match is found when it encounters the word beautiful. However, this would not work with match function as it will match the expression only with the beginning of the text.