import re


def _regex_search(regex, lines, first):
    """Remove all except 1 line that matches the regex.
    Returns the unique lines.

    regex: the regular expression to match
    lines: the lines of the file to deduplicate
    first: if the first match should be kept, if false, the last match is kept
    """
    unique_lines = []
    last_match = -1
    for line in lines:
        res = re.match(regex, line)
        if res is not None:
            if last_match < 0:
                unique_lines.append(line)
                last_match = len(unique_lines)-1
            elif last_match >= 0 and not first:
                unique_lines.pop(last_match)
                unique_lines.append(line)
                last_match = len(unique_lines)-1
        else:
            unique_lines.append(line)

    return unique_lines