1

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 2

1

Use the following approach:

pat = '.*(?P<word>\w+\d+\b).+'  # sample pattern
has_named_group = bool(re.search(r'\(\?P<\w+>[^)]+\)', pat))

This can also be a function:

def has_named_group(pat):
    return bool(re.search(r'\(\?P<\w+>[^)]+\)', pat))
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.