import re


def x_join(pattern, string, func, flags=0):
    """Apply a function to regexp matches.

    Each regexp match in string is substituted with the return value of
    func when called with the matched substring.
    """
    pattern = f'({pattern})'
    parts = []
    for i, substring in enumerate(re.split(pattern, string, flags)):
        if i % 2:
            parts.append(func(substring))
        else:  # Includes first and last
            parts.append(substring)
    return ''.join(parts)