Python program to understand difference between match() and search() methods

Here, we will see the difference between match() and search() methods using an example in Python.
Submitted by Shivang Yadav, on March 10, 2021

The match() method in Python is used to match patterns only at the beginning of the string. Whereas, the search() method is used to search patterns at any point in the string.

Program to illustrate the working of our solution

import re

myString = "learn python programming language at includehelp"
print("String : ",myString)

print("Matching regular expression in string using match() method.")
matchObj = re.match(r'at',myString,re.M|re.I)
if matchObj:
    print("Match Found!")
else:
    print("No Matches are found")

print("Searching regular expression in string using search() method.")
searchObj = re.search(r'at',myString,re.M|re.I)
if searchObj:
    print("Item Found!")
else:
    print("Item Not found")

Output:

String :  learn python programming language at includehelp
Matching regular expression in string using match() method.
No Matches are found
Searching regular expression in string using search() method.
Item Found!

Python Regular Expression Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.