import re


def allsubn(pattern, repl, string, count=0, flags=0):
    """Works just as re.subn, but works until there is no matches left."""
    total_count = 0
    cur_count = 1
    while cur_count:
        if count > 0:
            if total_count >= count:
                return (string, total_count)
            count_left = count - total_count
        else:
            count_left = 0
        (string, cur_count) = re.subn(pattern, repl, string, count=count_left, flags=flags)
        total_count += cur_count
    return (string, total_count)