python中的match对象

match.group()返回匹配对象的一个或多个分组。

  1. 不含参数的时候,返回整个匹配对象
  2. 含有一个参数的时候,返回参数对应分组的对象
  3. 含有多个参数的时候,以元组的形式返回参数对应的分组
>>> m = re.match(r"(\w+) (\w+)", "Isaac Newton, physicist")
>>> m.group(0)       # The entire match
'Isaac Newton'
>>> m.group(1)       # The first parenthesized subgroup.
'Isaac'
>>> m.group(2)       # The second parenthesized subgroup.
'Newton'
>>> m.group(1, 2)    # Multiple arguments give us a tuple.
('Isaac', 'Newton')

如果正则表达式中使用了(?<name>..)命名分组,那么group参数也可以传递相应的name来返回匹配的group。

>>> m = re.match(r"(?P<first_name>\w+) (?P<last_name>\w+)", "Malcolm Reynolds")
>>> m.group('first_name')
'Malcolm'
>>> m.group('last_name')
'Reynolds'

当然,此时也是可以使用数组表示相应的分组的。

>>> m.group(1)
'Malcolm'
>>> m.group(2)
'Reynolds'

match对象还有其他函数,如span(),start(),end(),string,re,pos,endpos,lastindex,lastgroup

In [68]: m.start()
Out[68]: 0

In [83]: m.start(1)
Out[83]: 0

In [84]: m.start(2)
Out[84]: 8

In [85]: m.end(1)
Out[85]: 7

In [87]: m.end(2)
Out[87]: 16

In [69]: m.end()
Out[69]: 16

In [70]: m.span()
Out[70]: (0, 16)

In [88]: m.span(1)
Out[88]: (0, 7)

In [89]: m.span(2)
Out[89]: (8, 16)

In [72]: m.string
Out[72]: 'Malcolm Reynolds'

In [73]: m.re
Out[73]: re.compile(r'(?P<first_name>\w+) (?P<last_name>\w+)', re.UNICODE)

In [74]: m.pos
Out[74]: 0

In [75]: m.endpos
Out[75]: 16

In [76]: m.lastindex #The integer index of the last matched capturing group, or None if no group was matched at all. For example, the expressions (a)b, ((a)(b)), and ((ab)) will have lastindex == 1 if applied to the string 'ab', while the expression (a)(b) will have lastindex == 2, if applied to the same string.
Out[76]: 2

In [77]: m.lastgroup #最后捕获分组的名称,如果没有分组被捕获或者捕获分组没有名字,那么结果为None
Out[77]: 'last_name'

其中的lastindex还是有点不太懂

groups([default]): 
以元组形式返回全部分组截获的字符串。相当于调用group(1,2,…last)。default表示没有截获字符串的组以这个值替代,默认为None。

groupdict([default]): 
返回以有别名的组的别名为键、以该组截获的子串为值的字典,没有别名的组不包含在内。default含义同上。

  • 9
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值