python正则-group()

最近要开始系统的学习一遍python的正则表达式,所以笔记还是要记起来滴。

python利用正则表达式匹配到的字符串,可以通过group()方法获取。

group()/group(0)

group(num)

groups()

举个栗子:

#!/usr/bin/python3
import re

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(0) : ", matchObj.group(0))
print ("matchObj.group(1) : ", matchObj.group(1))
print ("matchObj.group(2) : ", matchObj.group(2))
print ("matchObj.groups() : ", matchObj.groups())
else:
print ("No match!!")

执行结果:

>>>
('matchObj.group() : ', 'Cats are smarter than dogs')
('matchObj.group(0) : ', 'Cats are smarter than dogs')
('matchObj.group(1) : ', 'Cats')
('matchObj.group(2) : ', 'smarter')
('matchObj.groups() : ', ('Cats', 'smarter'))
>>>

由以上栗子可以得出关于group()各种使用方式的区别:

group()和group(0)效果一样,用于获取正则表达式匹配到的全部结果,参数默认0;

group(num),num为正整数,获取正则表达式匹配结果中相应的第n个括号内的元组;

groups(),用于获取正则表达式全部括号内的元组。

如果正则中没有用到括号,那么group()使用会报错:

Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
s.groups().get()
AttributeError: 'NoneType' object has no attribute 'groups'

 

posted on 2018-02-06 20:35  _小菜鸟  阅读(1128)  评论(0编辑  收藏  举报

导航