import re


def filter_variables(variables, variable_regex, is_whitelist):
    """Filter a list of variables based on the regex.
    Args:
        variables: a list of tf.Variable to be filtered.
        variable_regex: a regex specifying the filtering rule.
        is_whitelist: a bool. If True, indicate `variable_regex` specifies the
            variables to keep. If False, indicate `variable_regex` specfieis the
            variables to discard.
    Returns:
        filtered_variables: a list of tf.Variable after filtering.
    """
    if is_whitelist:
        filtered_variables = [
            v for v in variables if variable_regex is None or
            re.match(variable_regex, v.name)
        ]
    else:
        filtered_variables = [
            v for v in variables if variable_regex is None or
            not re.match(variable_regex, v.name)
        ]
    return filtered_variables