In this Tutorial, we are going to discuss the difference between re.search() and re.match() functions which are being used to get the matched String from an existing string, Either from Starting or in between the string.
Ways To Match Substring With Main Strings
There are some ways to check the matches of substrings with main strings. Although there are a number of ways to do so bot here we are going to discuss about rematch() and re.search() inbuild functions of python. Let’s discuss them one by one.
What re.match() Do?
It is an inbuilt function used to get the boolean result of comparing two strings. If they match the substring with a string from character zero to the end of the substring. That is if the substring matches as it is from starting then it will give a boolean result.
Either yes or no.
Note- It will give the result as yes only if the starting of the string matches with the existing String, In between matches will not be considered in the case of re.match(). So to overcome this issue we came up with re.search() Function which Let’s discuss.
research() Use In Python
As we discussed in the last paragraph how re.match() is used for simply checking starting string whereas in the case of re.search we can get yes if, at any of the times or locations, we found to match it will return as true as it does not specifically deal with starting string.
It scans through the whole of the string as a whole to get the result, as a result, it leads to checking the whole string and once the whole string is checked it gives the result so with this inbuild function we can get true irrespective of location.
Now let’s discuss all the possible ways to use both the inbuild functions and find out when they come true and when false in the case of both re.match(), and re.search() functions.
string_with_newlines = """something someotherthing""" import re print re.match('some', string_with_newlines) # matches print re.match('someother', string_with_newlines) # won't match print re.match('^someother', string_with_newlines, re.MULTILINE) # also won't match print re.search('someother', string_with_newlines) # finds something print re.search('^someother', string_with_newlines, re.MULTILINE) # also finds something m = re.compile('thing$', re.MULTILINE) print m.match(string_with_newlines) # no match print m.match(string_with_newlines, pos=4) # matches print m.search(string_with_newlines, re.MULTILINE) # also matche
As the code is self-explanatory where all the permutations and combinations are being explained for all the possibilities if both the functions.
Learn More about re.search() and re.match() at: https://stackoverflow.com/questions/180986/what-is-the-difference-between-re-search-and-re-match
And learn about Substrings and Strings at Some Basic Python String Programs-1