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

发布于 2025-01-10 21:27:52 字数 550 浏览 0 评论 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 的情况下测试该组是否存在 - - 因为这会使函数的其余部分短路,如果找不到指定的组,我仍然需要运行该函数。

I'm wondering what is the proper way to test if a named capture group exists. Specifically, I have a function that takes a compiled regex as an argument. The regex may or may not have a specific named group, and the named group may or may not be present in a string being passed in:

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

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")

I'd like to test if the group exists without using try -- as this would short circuit the rest of the function, which I would still need to run if the named group was not found.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

青瓷清茶倾城歌 2025-01-17 21:27:52

如果您想检查匹配数据对象是否包含命名组捕获,即命名组是否匹配,您可以使用MatchData#g​​roupdict() 属性:

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 演示。请注意,如果您需要布尔输出,只需使用 bool(...) 将表达式包装在 print 内即可: 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) 定义的任何符号组名称映射到组编号的字典。如果模式中没有使用符号组,则字典为空。

请参阅 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

If you want to check if a match data object contains a named group capture, i.e. if a named group matched, you can use the MatchData#groupdict() property:

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

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)

See the Python demo. Note that if you need a boolean output, simply wrap the expression inside print with bool(...): print(bool(match and 'idx' in match.groupdict())).

If you need to check if a group with a specific name exists in the compile pattern, you can use Pattern.groupindex to check if the group name exists:

def some_func(regex, group_name):
   return group_name in regex.groupindex

The documentation says:

Pattern.groupindex
A dictionary mapping any symbolic group names defined by (?P<id>) to group numbers. The dictionary is empty if no symbolic groups were used in the pattern.

See the Python demo:

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

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
云之铃。 2025-01-17 21:27:52

您可以检查 groupdict 匹配对象

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

You can check the groupdict of the match object:

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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文