I'm wondering what the proper way to test if a named capture group exists. Specifically, I have a function that takes a compiled regex as a parameter. 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
CodePudding user response:
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]*)?$")
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
CodePudding user response:
You can check the groupdict
of the match
object:
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