如何检查命名捕获组是否存在?

Har*_*nry 6 python regex python-re

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

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")
Run Code Online (Sandbox Code Playgroud)

我想测试该组是否存在而不使用try-- 因为这会短路函数的其余部分,如果找不到指定的组,我仍然需要运行该函数。

Wik*_*żew 9

如果您想检查匹配数据对象是否包含命名组捕获,即命名组是否匹配,您可以使用以下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)
Run Code Online (Sandbox Code Playgroud)

请参阅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
Run Code Online (Sandbox Code Playgroud)

文档说:

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
Run Code Online (Sandbox Code Playgroud)


Jan*_*asa 1

您可以检查groupdict对象match

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
Run Code Online (Sandbox Code Playgroud)