import re


def replace_links(text, link_patterns):
    """
    A little function that will replace string patterns in text with
    supplied hyperlinks.  'text' is just a string, most often a field
    in a django or flask model.  link_pattern is a list of two element
    dictionaries.  Each dicationary must have keys 'pattern' and
    'url'.  'pattern' is the regular expression to apply to the text
    while url is the text to be used as its replacement.  Regular
    expression call backs are supported.  See the python documentation
    for re.sub for more details.

    Note: The function does not make any attempt to validate the link or
    the regex pattern.

    """


    for pattern in link_patterns:
        regex = re.compile(pattern.get("pattern"), re.IGNORECASE)
        if "project:" in pattern.get("pattern"):
            # mark down replace _ with ems - replace them first:
            text = re.sub(r"</?em>", "_", text)
            prj_codes = regex.findall(text)
            for x in prj_codes:
                link = pattern["url"]
                href = link.format(x.lower(), x.upper())
                text = text.replace(x, href)
        else:
            text = re.sub(regex, pattern["url"], text)
    return text