import re


def finditer_with_line_numbers(pattern, input_string, flags=0):
    """
    A version of 're.finditer' that returns '(match, line_number)' pairs.
    """

    matches = list(re.finditer(pattern, input_string, flags))
    if not matches:
        return []

    end = matches[-1].start()
    # -1 so a failed 'rfind' maps to the first line.
    newline_table = {-1: 0}
    for i, m in enumerate(re.finditer(r'\n', input_string), 1):
        # don't find newlines past our last match
        offset = m.start()
        if offset > end:
            break
        newline_table[offset] = i

    # Failing to find the newline is OK, -1 maps to 0.
    for m in matches:
        newline_offset = input_string.rfind('\n', 0, m.start())
        line_number = newline_table[newline_offset]
        yield m, line_number