开发者社区> 问答> 正文

Python里面search()和match()的区别?

Python里面search()和match()的区别?

展开
收起
珍宝珠 2019-11-11 12:41:31 2318 0
1 条回答
写回答
取消 提交回答
  • 它们两个都在re模块中

    match()函数是在string的开始位置匹配,如果不匹配,则返回None;
    search()会扫描整个string查找匹配;

    match()

    >>> import re
    >>> print(re.match('hello','helloworld').span())  # 开头匹配到
    (0, 5)
    >>> print(re.match('hello','nicehelloworld').span()) # 开头没有匹配到
    Traceback (most recent call last):
      File "<pyshell#2>", line 1, in <module>
        print(re.match('hello','nicehelloworld').span())
    AttributeError: 'NoneType' object has no attribute 'span'
    >>>
    

    search()

    >>> print(re.search('a','abc'))
    <_sre.SRE_Match object; span=(0, 1), match='a'>
    >>> print(re.search('a','bac').span())
    (1, 2)
    >>>
    

    结论:match() 使用限制更多

    2019-11-11 13:45:01
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
From Python Scikit-Learn to Sc 立即下载
Data Pre-Processing in Python: 立即下载
双剑合璧-Python和大数据计算平台的结合 立即下载