如何检查命名捕获组是否存在?
我想知道测试命名捕获组是否存在的正确方法是什么。具体来说,我有一个函数将编译的正则表达式作为参数。正则表达式可能有也可能没有特定的命名组,并且命名组可能会也可能不会出现在传入的字符串中:
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("^barquot;)
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您想检查匹配数据对象是否包含命名组捕获,即命名组是否匹配,您可以使用
MatchData#groupdict()
属性:请参阅 Python 演示。请注意,如果您需要布尔输出,只需使用
bool(...)
将表达式包装在print
内即可:print(bool(match and 'idx' in match.groupdict()))
。如果需要检查编译模式中是否存在具有特定名称的组,可以使用
Pattern.groupindex
检查组名称是否存在:文档说:
请参阅 Python 演示:
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:See the Python demo. Note that if you need a boolean output, simply wrap the expression inside
print
withbool(...)
: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:The documentation says:
See the Python demo:
您可以检查
groupdict
匹配
对象:You can check the
groupdict
of thematch
object: