Matching Versus Searching in Python



Python offers two different primitive operations based on regular expressions: match checks for a match only at the beginning of the string, while search checks for a match anywhere in the string (this is what Perl does by default).

Example

 Live Demo

#!/usr/bin/python
import re
line = "Cats are smarter than dogs";
matchObj = re.match( r'dogs', line, re.M|re.I)
if matchObj:
   print "match --> matchObj.group() : ", matchObj.group()
else:
   print "No match!!"
searchObj = re.search( r'dogs', line, re.M|re.I)
if searchObj:
   print "search --> searchObj.group() : ", searchObj.group()
else:
   print "Nothing found!!"

Output

When the above code is executed, it produces the following result −

No match!!
search --> searchObj.group() : dogs
Updated on: 2020-01-30T07:31:11+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements