The difference between re.match and re.search

The difference between re.match and re.search

re.match only matches the beginning of the string. If the string does not match the regular expression at the beginning, the match fails and the function returns None; while re.search matches the entire string until a match is found.

Examples:

#!/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!!"

matchObj = re.search( r'dogs', line, re.M|re.I)
if matchObj:
   print "search --> matchObj.group() : ", matchObj.group()
else:
   print "No match!!"
The results of the above examples are as follows:

Guess you like

Origin blog.csdn.net/huochuangchuang/article/details/50359547