Merger
Merger

Reputation: 45

Python regex - check if pattern contains capturing named group

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.

Upvotes: 1

Views: 149

Answers (2)

The fourth bird
The fourth bird

Reputation: 163362

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

Upvotes: 1

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

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

Upvotes: 1

Related Questions