Compile regex from pattern and pattern_dict

def compile_regex(self, pattern, flags=0):
        """Compile regex from pattern and pattern_dict"""
        pattern_re = regex.compile('(?P<substr>%\{(?P<fullname>(?P<patname>\w+)(?::(?P<subname>\w+))?)\})')
        while 1:
            matches = [md.groupdict() for md in pattern_re.finditer(pattern)]
            if len(matches) == 0:
                break
            for md in matches:
                if md['patname'] in self.pattern_dict:
                    if md['subname']:
                        # TODO error if more than one occurance
                        if '(?P<' in self.pattern_dict[md['patname']]:
                            # this is not part of the original logstash implementation 
                            # but it might be useful to be able to replace the
                            # group name used in the pattern
                            repl = regex.sub('\(\?P<(\w+)>', '(?P<%s>' % md['subname'],
                                self.pattern_dict[md['patname']], 1)
                        else:
                            repl = '(?P<%s>%s)' % (md['subname'], 
                                self.pattern_dict[md['patname']])
                    else:
                        repl = self.pattern_dict[md['patname']]
                    # print "Replacing %s with %s"  %(md['substr'], repl)
                    pattern = pattern.replace(md['substr'], repl)
                else:
                    # print('patname not found')
                    # maybe missing path entry or missing pattern file?
                    return
        # print 'pattern: %s' % pattern
        return regex.compile(pattern, flags)