您好,欢迎来到华拓网。
搜索
您的当前位置:首页正文

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

2024-07-17 来源:华拓网

在我们最早接触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学习指路:

Copyright © 2019- huatuo3.cn 版权所有 湘ICP备2023017654号-3

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务