def filter_names(names, text=""):
    """
    Returns elements in a list that match a given substring.
    Can be used in conjnction with compare_varnames to return a subset
    of variable names pertaining to a given diagnostic type or species.

    Args:
    -----
        names: list of str
            Input list of names.

        text: str
            Target text string for restricting the search.
    
    Returns:
    --------
        filtered_names: list of str
            Returns all elements of names that contains the substring
            specified by the "text" argument.  If "text" is omitted,
            then the original contents of names will be returned.
        
    Examples:
    ---------
        Obtain a list of variable names that contain the substrings
        "CO", "NO", and "O3":
        
        >>> import gcpy
        >>> import xarray as xr
        >>> refdata = xr.open_dataset("ref_data_file.nc")
        >>> devdata = xr.open_dataset("dev_data_file.nc")
        >>> vardict = gcpy.compare_varnames(refdata, devdata)
        >>> var_CO = gcpy.filter_names(vardict['commonvars'], "CO")
        >>> var_NO = gcpy.filter_names(vardict['commonvars'], "NO")
        >>> var_O3 = gcpy.filter_names(vardict['commonvars'], "O3")
    """

    if text != "":
        filtered_names = [k for k in names if text in k]
    else:
        filtered_names = [k for k in names if k]

    return filtered_names