0

我想知道测试命名捕获组是否存在的正确方法。具体来说,我有一个将编译的正则表达式作为参数的函数。正则表达式可能有也可能没有特定的命名组,命名组可能存在也可能不存在于传入的字符串中:

some_regex = re.compile("^foo(?P<idx>[0-9]*)?$")
other_regex = re.compile("^bar$")

def some_func(regex, string):
    m=regex.match(regex,string)
    if m.group("idx"):     # get *** IndexError: no such group here...
        print(f"index found and is {m.group('idx')}")
    print(f"no index found")

some_func(other_regex,"bar")

我想在不使用的情况下测试该组是否存在try——因为这会使函数的其余部分短路,如果找不到命名的组,我仍然需要运行该函数

4

2 回答 2

3

如果要检查匹配数据对象是否包含命名组捕获,即是否匹配命名组,可以使用以下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 演示。请注意,如果您需要布尔输出,只需将表达式printbool(...):包装起来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
于 2022-03-01T13:33:53.307 回答
2

您可以检查对象groupdictmatch

import re
some_regex = re.compile("^foo(?P<idx>[0-9]*)?$")

match = some_regex.match('foo11')
print(True) if match and 'idx' in match.groupdict() else print(False) # True
match = some_regex.match('bar11')
print(True) if match and 'idx' in match.groupdict() else print(False) # False
于 2022-03-01T13:45:51.727 回答