Python里面search()和match()的区别是什么【面试题详解附代码】

今天爱分享给大家带来Python里面search()和match()的区别是什么【面试题详解附代码】,希望能够帮助到大家。
它们两个都在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 "", line 1, in 

    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() 使用限制更多

原文链接:https://blog.itblood.com/2368.html,转载请注明出处。
0
火影忍者:被查克拉束缚v0.15 AI版[PC+安卓/1.20G/更新]Naruto:Bound by Chakra [v0.15] [同人SLG/汉化/沙盒]
火影忍者:被查克拉束缚v0.15 AI版[PC+安卓/1.20G/更新]Naruto:Bound by Chakra [v0.15] [同人SLG/汉化/沙盒]
10分钟前 有人购买 去瞅瞅看

站点公告

显示验证码
没有账号?注册  忘记密码?