import re


def _get_valid_filter_terms(filter_terms, colnames):
    """Removes any filter terms referencing non-existent columns

    Parameters
    ----------
    filter_terms
        A list of terms formatted so as to be used in the `where` argument of
        :func:`pd.read_hdf`.
    colnames :
        A list of column names present in the data that will be filtered.

    Returns
    -------
        The list of valid filter terms (terms that do not reference any column
        not existing in the data). Returns none if the list is empty because
        the `where` argument doesn't like empty lists.

    """
    if not filter_terms:
        return None
    valid_terms = filter_terms.copy()
    for term in filter_terms:
        # first strip out all the parentheses - the where in read_hdf
        # requires all references to be valid
        t = re.sub('[()]', '', term)
        # then split each condition out
        t = re.split('[&|]', t)
        # get the unique columns referenced by this term
        term_columns = set([re.split('[<=>\s]', i.strip())[0] for i in t])
        if not term_columns.issubset(colnames):
            valid_terms.remove(term)
    return valid_terms if valid_terms else None