Issue
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
Solution
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
Answered By - Jan Christoph Terasa
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.