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]*)?$")
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")
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.