Home > Blockchain >  Python regex - check if pattern contains capturing named group
Python regex - check if pattern contains capturing named group

Time:01-07

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.

CodePudding user response:

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