import re


def replace(s, pattern, replacement):
    """Replaces occurrences of a match string in a given
    string and returns the new string. The match string
    can be a regex expression.

    Args:
        s (str):           the string to modify
        pattern (str):     the search expression
        replacement (str): the string to replace each match with
    """
    # the replacement string may contain invalid backreferences (like \1 or \g)
    # which will cause python's regex to blow up. Since this should emulate
    # the jam version exactly and the jam version didn't support
    # backreferences, this version shouldn't either. re.sub
    # allows replacement to be a callable; this is being used
    # to simply return the replacement string and avoid the hassle
    # of worrying about backreferences within the string.
    def _replacement(matchobj):
        return replacement
    return re.sub(pattern, _replacement, s)