微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

正则表达式re

 

一、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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐