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).


 Live Demo

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


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

No match!!
search --> : dogs

Updated on: 30-Jan-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started