匹配对象的子组 Match.group([group1, ...])
>>> 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')
由括号包含的表达式为一个子组,如上述代码的(\w+)
,根据所在位置,可使用.group(index)
index∈1,2
来获取。
为子组命名 (?P<name>...)
使用(?P<name>...)
>>> m = re.match(r"(?P<first_name>\w+) (?P<last_name>\w+)", "Malcolm Reynolds")
>>> m.group('first_name')
'Malcolm'
>>> m.group('last_name')
'Reynolds'
元组形式获取所有子组的匹配 Match.groups(default=None)
>>> m = re.match(r"(\d+)\.(\d+)", "24.1632")
>>> m.groups()
('24', '1632')
字典形式获取所有子组的匹配 Match.groupdict(default=None)
>>> m = re.match(r"(?P<first_name>\w+) (?P<last_name>\w+)", "Malcolm Reynolds")
>>> m.groupdict()
{'first_name': 'Malcolm', 'last_name': 'Reynolds'}
子组匹配到的字串的开始和结束标号 Match.start([group])
Match.end([group])
m.string[m.start(g):m.end(g)]
等价于m.group(g)
元组形式的子组匹配到的字串的开始和结束标号Match.span([group])
返回一个二元组 (m.start(group), m.end(group))
。 如果 group 没有在这个匹配中,就返回 (-1, -1) 。group 默认为0,就是整个匹配。
[1] Python re 文档 https://docs.python.org/zh-cn/3/library/re.html