品易云推流 关闭
文章详情页
文章 > Python > python re.match和re.search的不同使用

python re.match和re.search的不同使用

头像

小妮浅浅

2021-02-25 14:32:275633浏览 · 0收藏 · 0评论

在我们最早接触python的模块中,re可以说是比较频繁使用的了。不过有些人对于其中的知识点进行混淆,常见的出错是re.match和re.search使用范围上的差别。这里我们对它们的不同点进行了区分,同时带来了re模块不同函数的实例使用方法,下面我们一起来学习下吧。

1、re.match与re.search的区别

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

2、使用实例

re.match

import re  
  
text = "JGood is a handsome boy, he is cool, clever, and so on..."  
m = re.match(r"(/w+)/s", text)  
if m:  
    print m.group(0), '/n', m.group(1)  
else:  
print 'not match'

re.search

import re  
  
text = "JGood is a handsome boy, he is cool, clever, and so on..."  
m = re.search(r'/shan(ds)ome/s', text)  
if m:  
    print m.group(0), m.group(1)  
else:  
    print 'not search'

以上就是python re.match和re.search的不同使用,相信看完全面文章后,大家已经能对这两个不同re模块的函数有所区分了,下次使用时不要再出错啦更多Python学习指路:python基础教程

关注

关注公众号,随时随地在线学习

本教程部分素材来源于网络,版权问题联系站长!

底部广告图