import re


def _apply_keyword_filters(results, tokens):
    """Filters results that match the given keywords (tokens).

    Arguments:
        results: List of search result plugins.
        tokens: Keywords to filter results on.

    Returns:
        List of plugins that match the given keywords.
    """
    if tokens:
        # Create a regex that matches a string S iff for each keyword K in
        # `search` there is a corresponding word in S that begins with K.
        tokens_regex = (r'\b%s' % re.escape(t) for t in tokens)
        search_regex = re.compile('.*'.join(tokens_regex))

        # Surprisingly, regex matching like this is slightly faster than
        # prefix-matching two sorted lists of tokens.
        results = filter(lambda plugin:
                search_regex.search(plugin['keywords']), results)

    return results