Difference between the search() and match() in regular expression in python by R4R Team

- search() :

Syntax-
re.search(pattern,string)

match():

Syntax-
re.match(pattern,string,flag=0)

-Both of the function are used to match the pattern to the string in regular expression.

Difference-

match() function search the pattern only at the starting of the string.
while search() function search the pattern in whole string.

Example-

string is s="this is string"
re.match('is',s) will not match.
re.search('is',s) will match.


program-

#import the re module
import re

#Given string is
s = "This is programming language"

#search by match() function
x=re.match('is',s)
if x:
print("Matched by match() function")
else:
print("Not matched")

#search by search()
function
x=re.search('is',s)
if x:
print("Matched by search() function")
else:
print("Not matched")


output-

Not matched
Matched by search() function


-In this program, we have a string "This is programming language" then we search the 'is' in this string by both match() and search() function.
- search() function match this with string but match() function don't because 'is' was not present at the starting of the string.




Leave a Comment:
Search
Categories
R4R Team
R4Rin Top Tutorials are Core Java,Hibernate ,Spring,Sturts.The content on R4R.in website is done by expert team not only with the help of books but along with the strong professional knowledge in all context like coding,designing, marketing,etc!