Open In App
Related Articles

Python | vs re.match()

Improve Article
Save Article
Like Article

Prerequisite: Regex in Python

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

There is a difference between the use of both functions. Both return the first match of a substring found in the string, but re.match() searches only from the beginning of the string and return match object if found. But if a match of substring is found somewhere in the middle of the string, it returns none. 
While 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 : 


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

Output : 

<re.Match object; span=(75, 81), match='string'>
<re.Match object; span=(0, 6), match='string'>
<re.Match object; span=(0, 6), match='string'>

Conclusion : 

  1. is returning match object and implies that first match found at index 69.
  2. re.match() is returning none because match exists in the second line of the string and re.match() only works if the match is found at the beginning of the string. 
  3. re.IGNORECASE is used to ignore the case sensitivity in the strings. 
  4. Both and re.match() returns only the first occurrence of a substring in the string and ignore others. 
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 09 Aug, 2021
Like Article
Save Article
Similar Reads
Related Tutorials