import re


def extract_sample_name(has_a_sample, sample_names):
    """
    Useful for matching sample names in larger strings such as fastq file names.

    Note that we must sort the samples names by length in order to return the longest match:
    e.g. sample_abc123-IGO-XXX, [sample_abc123, sample_abc12] --> sample_abc123

    :param: has_a_sample String that has a Sample ID inside (usually a file path)
    :param: sample_names String[] that contains all possible sample IDs to be found in `has_a_sample`
            Note that if the target sample ID is not in this list, the wrong sample ID may be returned.
    """
    sample_names = sorted(sample_names, key=len, reverse=True)
    sample_name_search = r"|".join(sample_names)
    sample_name_search = r".*(" + sample_name_search + ").*"
    return re.sub(sample_name_search, r"\1", has_a_sample)