def replace_named_groups(pattern):
 named_group_indices = [(m.start(0), m.end(0), m.group(1)) for m in named_group_matcher.finditer(pattern)]
 group_pattern_and_name = []
 for (start, end, group_name) in named_group_indices:
  (unmatched_open_brackets, prev_char) = (1, None)
  for (idx, val) in enumerate(list(pattern[end:])):
   if (unmatched_open_brackets == 0):
    group_pattern_and_name.append((pattern[start:(end + idx)], group_name))
    break
   if ((val == '(') and (prev_char != '\\')):
    unmatched_open_brackets += 1
   elif ((val == ')') and (prev_char != '\\')):
    unmatched_open_brackets -= 1
   prev_char = val
 for (group_pattern, group_name) in group_pattern_and_name:
  pattern = pattern.replace(group_pattern, group_name)
 return pattern

def replace_named_groups ( pattern ) : named_group_indices = [ ( m . start ( 0 ) , m . end ( 0 ) , m . group ( 1 ) ) for m in named_group_matcher . finditer ( pattern ) ] group_pattern_and_name = [ ] for ( start , end , group_name ) in named_group_indices : ( unmatched_open_brackets , prev_char ) = ( 1 , None ) for ( idx , val ) in enumerate ( list ( pattern [ end : ] ) ) : if ( unmatched_open_brackets == 0 ) : group_pattern_and_name . append ( ( pattern [ start : ( end + idx ) ] , group_name ) ) break if ( ( val == '(' ) and ( prev_char != '\\' ) ) : unmatched_open_brackets += 1 elif ( ( val == ')' ) and ( prev_char != '\\' ) ) : unmatched_open_brackets -= 1 prev_char = val for ( group_pattern , group_name ) in group_pattern_and_name : pattern = pattern . replace ( group_pattern , group_name ) return pattern
find named groups in pattern and replace them with the group name .