Home  >  Article  >  Backend Development  >  A brief explanation of the difference between re.search and re.match in the Python Re module

A brief explanation of the difference between re.search and re.match in the Python Re module

Tomorin
TomorinOriginal
2018-08-15 13:55:143221browse

In the two previous articles "What is the python re.match function, understand the use of the python match function" and "Detailed explanation of the python re.search method in Python", we introduced the match module and search module of the Re module in Python , this article is linked to the previous two articles to explain the difference between re.search and re.match

What is re.search:

See article"Detailed explanation of python re.search method in Python".

What is re.match:

See the article: "What is the python re.match function, understand the use of the python match function".

So what is the difference between re.search and re.match?

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


instance is found:

#!/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 example are as follows:

No match!!
search --> matchObj.group() :  dogs


The above is the detailed content of A brief explanation of the difference between re.search and re.match in the Python Re module. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn