Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python — check if named capture group exists

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 {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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading