How can I check whether regex pattern contains a named capturing group? I want to decide whether to use re.findall or re.finditer based on the form of the regex.
2 Answers
You can use Pattern.groupindex
A dictionary mapping any symbolic group names defined by (?P) to group numbers. The dictionary is empty if no symbolic groups were used in the pattern.
For example
import re
pattern = re.compile('(?P<mygroup>.*)')
if pattern.groupindex:
print("The pattern contains a named capturing group")
else:
print("The pattern does not contain a named capturing group")
Output
The pattern contains a named capturing group