Python | re.search() vs re.match()

Prerequisite: Regex in Python

Use of re.search() and re.match() –
re.search() and re.match() both are functions of re module in python. These function are very efficient and fast for searching in strings. The function searches for some substring in a string and return a match object if found, else it returns none.

re.search() vs re.match() –
There is a difference between the use of both functions. Both return first match of a substring found in the string, but re.match() searches only in the first line of the string and return match object if found, else return none. But if a match of substring is found in some other line other than the first line of string (in case of a multi-line string), it returns none.
While re.search() searches for the whole string even if the string contains multi-lines and tries to find a match of the substring in all the lines of string.



Example :

filter_none

edit
close

play_arrow

link
brightness_4
code

# import re module
import re
  
Substring ='string'
  
  
String ='''We are learning regex with geeksforgeeks 
         regex is very useful for string matching.
          It is fast too.'''
  
# Use of re.search() Method
print(re.search(Substring, String, re.IGNORECASE))
  
# Use of re.match() Method
print(re.match(Substring, String, re.IGNORECASE))

chevron_right


Output :

<_sre.SRE_Match object; span=(69, 75), match='string'>
None

Conclusion :

  1. re.search() is returning match object and implies that first match found at index 69.
  2. re.match() is returning none because match exist in second line of the string and re.match() searches only in first line of string.
  3. re.IGNORECASE is used to ignore the case sensitivity in the strings.
  4. Both re.search() and re.match() returns only first occurrence of substring in string and ignore others.


My Personal Notes arrow_drop_up

Love to write, Competitive programming is fun, Python is way

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.