PHP前端开发

简诉Python Re模块中re.search和re.match的区别

百变鹏仔 2小时前 #Python
文章标签 模块

先前的两篇文章《python re.match函数是什么,了解python match函数的使用》,《python中的python re.search方法详解》,我们介绍了python中re模块的match模块和search模块,这边文章就是与前两篇联动说明re.search和re.match的区别

什么是re.search

参见文章《Python中的python re.search方法详解》。

什么是re.match:

参见文章:《python re.match函数是什么,了解python match函数的使用》。

立即学习“Python免费学习笔记(深入)”;

那么re.search和re.match的区别是什么

简而言之是re.match只匹配字符串的开始,如果字符串开始不符合正则表达式,则匹配失败,函数返回None;而re.search匹配整个字符串,直到找到一个匹配

实例:

#!/usr/bin/pythonimport reline = "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!!"

以上实例运行结果如下:

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