如果要检查匹配数据对象是否包含命名组捕获,即是否匹配命名组,可以使用以下MatchData#groupdict()
属性:
import re
some_regex = re.compile("^foo(?P<idx>[0-9]*)?$")
match = some_regex.match('foo11')
print(match and 'idx' in match.groupdict()) # => True
match = some_regex.match('bar11')
print(match and 'idx' in match.groupdict()) # => None (coerceable to False)
请参阅Python 演示。请注意,如果您需要布尔输出,只需将表达式print
用bool(...)
:包装起来print(bool(match and 'idx' in match.groupdict()))
。
如果您需要检查编译模式中是否存在具有特定名称的组,您可以使用Pattern.groupindex
检查组名是否存在:
def some_func(regex, group_name):
return group_name in regex.groupindex
文档说:
Pattern.groupindex
将定义的任何符号组名称映射(?P<id>)
到组编号的字典。如果模式中没有使用符号组,则字典为空。
请参阅Python 演示:
import re
some_regex = re.compile("^foo(?P<idx>[0-9]*)?$")
other_regex = re.compile("^bar$")
def some_func(regex, group_name):
return group_name in regex.groupindex
print(some_func(some_regex,"bar")) # => False
print(some_func(some_regex,"idx")) # => True
print(some_func(other_regex,"bar")) # => False
print(some_func(other_regex,"idx")) # => False