# Group(), Groups(),& Groupdict() 用法

group()

>>> 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')
In [2]: m = re.match(r"(..)+", "a1b2c3")  # 三次匹配
In [3]: m.group(0)                        # 返回整个匹配串
Out[3]: 'a1b2c3'
In [4]: m.group(1)                        # 只返回最后一个匹配
Out[4]: 'c3'
In [5]: m.group(2)
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-5-9b74dc8a1297> in <module>()
----> 1 m.group(2)
IndexError: no such group

groups()

>>> m = re.match(r"(\d+)\.(\d+)", "24.1632")
>>> m.groups()
('24', '1632')


groupdict()

>>> m = re.match(r'(?P<user>\w+)@(?P<website>\w+)\.(?P<extension>\w+)','myname@hackerrank.com')
>>> m.groupdict()
{'website': 'hackerrank', 'user': 'myname', 'extension': 'com'}

posted @ 2019-02-10 11:29  joneylulu  阅读(450)  评论(0编辑  收藏  举报