Try it here
Subscribe
Python regular expression functions

Difference between re.match(), re.search() and re.findall()

difference_between_re.match(),_re.search()_and_re.findall()

re.match()

The re.match() method finds match if it occurs at start of the string.

Ex.

Find pattern 'DE' in 'DE - dEexms A learning website, DE'

>>> import re
>>> res = re.match('DE', 'DE - dEexms A learning website, DE')
>>> res

>>> res.group(0)
'DE'
>>> 

Now if we find pattern 'DE' in 'dEexms A learning website, DE', it will None as there is no match at start of the string.

>>> res = re.match('DE', 'dEexms A learning website, DE')
>>> print(res)
None
>>>

re.search()

The re.search() method is similar to re.match() but it doesn’t limit us to find matches at the beginning of the string only. re.search() searches for the whole string even if the string contains multi-lines and tries to find a match of the sub-string in all the lines of string.

Ex.

>>> res = re.search('DE', 'DE - dEexms A learning website, DE')
>>> res

>>> res.group(0)
'DE'

Now when pattern is not at beginning of the string

>>> res = re.search('DE', 'dEexms A learning website, DE')
>>> res

>>> res.group(0)
'DE'
>>> 

re.findall()

The re.findall() returns a list of all matching patterns. It searches from start or end of the given string. findall returns all occurrences of the pattern in list format. While searching a pattern, it is recommended to use re.findall() always, it works like re.search() and re.match() both.

Ex.

>>> res = re.findall('DE', 'DE - dEexms A learning website, DE')
>>> res
['DE', 'DE']

Writer profile pic

Amit on Sep 05, 2020 at 08:09 am


This article is contributed by Amit. If you like dEexams.com and would like to contribute, you can write your article here or mail your article to admin@deexams.com . See your article appearing on the dEexams.com main page and help others to learn.



Post Comment

Comments( 0)

×

Forgot Password

Please enter your email address below and we will send you information to change your password.