• 技术文章 >头条 >Python

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

    小妮浅浅小妮浅浅2021-02-25 14:32:27原创5310

    在我们最早接触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基础教程

    专题推荐:python rematch research
    品易云
    上一篇:python2和3同时安装在windows环境 下一篇:谷歌升级为Python软件基金会的顶级赞助商

    相关文章推荐

    • Python如何定制日志输出格式• python字符串的翻转实现的两种方法• Python中json模块有哪些函数• python字符串的拆分与合并• pickle模块在Python的函数使用• python中如何统计列表中元素出现的频率?

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网