import re


def replace_regex_link(pages, regex, basename, link):
    """Replace links in a bunch of pages based on a regex."""
    regex = r'( |^|\n)%s([,. $])' % regex
    for subdir in pages:
        for page in pages[subdir]:
            content = pages[subdir][page]
            if (basename not in page or basename == "Quattor") and basename in content:
                content = re.sub(regex, "\g<1>[%s](%s)\g<2>" % (basename, link), content)
                pages[subdir][page] = content
    return pages