gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 01:04:51 24 4
gpt4 key购买 nike

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

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 的情况下测试该组是否存在——因为这会使函数的其余部分短路,如果找不到命名组,我仍然需要运行该函数.

最佳答案

如果要检查匹配数据对象是否包含命名组捕获,即是否匹配命名组,可以使用 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 demo .请注意,如果您需要 bool 输出,只需将表达式包装在 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
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.

Python demo :

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

关于python - 如何检查命名的捕获组是否存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71309179/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com