• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

python正则表达式函数match()和search()的区别详解

python 搞java代码 3年前 (2022-05-21) 14次浏览 已收录 0个评论

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"

www#gaodaima.com来源gaodai$ma#com搞$$代**码网搞代码

结果是: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

来源:搞代码网:原文地址:https://www.gaodaima.com


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:python正则表达式函数match()和search()的区别详解

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址