• 企业400电话
  • 微网小程序
  • AI电话机器人
  • 电商代运营
  • 全 部 栏 目

    企业400电话 网络优化推广 AI电话机器人 呼叫中心 网站建设 商标✡知产 微网小程序 电商运营 彩铃•短信 增值拓展业务
    Python中正则表达式match()、search()函数及match()和search()的区别详解

    match()和search()都是python中的正则匹配函数,那这两个函数有何区别呢?

    match()函数只检测RE是不是在string的开始位置匹配, search()会扫描整个string查找匹配, 也就是说match()只有在0位置匹配成功的话才有返回,如果不是开始位置匹配成功的话,match()就返回none

    例如:

    #! /usr/bin/env python
    # -*- coding=utf-8 -*-
    import re
    text = 'pythontab'
    m = re.match(r"\w+", text)
    if m: 
      print m.group(0)
    else:
      print 'not match'

    结果是:pythontab

    而:

    #! /usr/bin/env python
    # -*- coding=utf-8 -*-
    #
    import re
    text = '@pythontab'
    m = re.match(r"\w+", text)
    if m: 
      print m.group(0)
    else:
      print 'not match'

    结果是:not match

    search()会扫描整个字符串并返回第一个成功的匹配

    例如:

    #! /usr/bin/env python
    # -*- coding=utf-8 -*-
    #
    import re
    text = 'pythontab'
    m = re.search(r"\w+", text)
    if m: 
      print m.group(0)
    else:
      print 'not match'
    
    

    结果是:pythontab

    那这样呢:

    #! /usr/bin/env python
    # -*- coding=utf-8 -*-
    #
    import re
    text = '@pythontab'
    m = re.search(r"\w+", text)
    if m: 
      print m.group(0)
    else:
      print 'not match'

    结果是:pythontab

    总结:

    Python中正则表达式match()函数

    如果不创建pattern对象,我们使用match函数可以直接进行正则表达式的匹配,在我看来这种方式更简洁,不过不适合大型程序的编写,后期维护可能会产生困难,不过编写一些小脚本完全可以胜任。

    Python中正则表达式search()函数

    search函数和match函数有点类似,都可以匹配模式,但是match和search函数也有区别,而且区别很大,match函数只能够字符串的开始位置开始匹配,而search是可以匹配字符串的任意位置,但也是返回找到的第一个匹配的模式。我们通过例子来了解这俩之间的区别吧。


    您可能感兴趣的文章:
    • 浅谈Python中re.match()和re.search()的使用及区别
    • python 使用re.search()筛选后 选取部分结果的方法
    • python使用正则表达式的search()函数实现指定位置搜索功能
    • Python-re中search()函数的用法详解(查找ip)
    上一篇:iOS中使用正则表达式NSRegularExpression 来验证textfiled输入的内容
    下一篇:Python正则表达式操作指南
  • 相关文章
  • 

    © 2016-2020 巨人网络通讯

    时间:9:00-21:00 (节假日不休)

    地址:江苏信息产业基地11号楼四层

    《增值电信业务经营许可证》 苏B2-20120278

    Python中正则表达式match()、search()函数及match()和search()的区别详解 Python,中,正则,表达式,match,