import re


def filter_by_category(result, name_filter=None):
    """ Filter by category name the result returned from ZIA.

    :param result: Dict of categories from ZIA response.
    :param name_filter: A regex string used to filter result.
    :return: Filtered result.
    """
    categories = result.get("categories", [])
    regex = r'{}'.format(name_filter)
    # Add category total and filtered counts to result.
    result.update({
        "category_counts": {
            "total": len(categories),
            "filtered": len(categories)
        }
    })

    if name_filter:
        filtered_categories = [c for c in categories if re.search(regex, c.get("configuredName", ''), re.I)]
        result["categories"] = filtered_categories
        result["category_counts"]["filtered"] = len(filtered_categories)

    return result