加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

正则表达式re

发布时间:2020-12-14 06:17:29 所属栏目:百科 来源:网络整理
导读:? 一、re模块的group和groups ? ? ? group 和 groups 是两个不同的函数 ? ? ? m.group()== m.group(0) ==?返回所有匹配到的字符 ? ? ? m.group(N) 返回第N组括号匹配到的字符 ? ? ? ?m.groups() 返回所有括号匹配到的字符,以元组格式存储 ? ? ?m.groups() =

?

一、re模块的group和groups

? ? ? group 和 groups 是两个不同的函数

? ? ? m.group()== m.group(0) ==?返回所有匹配到的字符

? ? ? m.group(N) 返回第N组括号匹配到的字符

?

? ? ?m.groups() 返回所有括号匹配到的字符,以元组格式存储

? ? ?m.groups() = (m.group(1),m.group(2),....)

?

? ? 测试数据:

? ??

line = "Cats are smarter than dogs"

matchObj = re.match(r‘(.*) are (.*?) .*‘,line,re.M | re.I)

if matchObj:
print("matchObj.group: ",matchObj.group)
print("matchObj.group() : ",matchObj.group())
print("matchObj.group() : ",matchObj.group(0))
print("matchObj.group(1) : ",matchObj.group(1))
print("matchObj.group(2) : ",matchObj.group(2))
else:
print("No match!!")

print(matchObj.groups())
print(matchObj.groups()[0])
print(matchObj.groups()[1])


测试结果:

  matchObj.group: <built-in method group of _sre.SRE_Match object at 0x10f5ffe00>  matchObj.group() : Cats are smarter than dogs  matchObj.group() : Cats are smarter than dogs  matchObj.group(1) : Cats  matchObj.group(2) : smarter  (‘Cats‘,‘smarter‘)  Cats  smarter

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读