human
Complete this python program:
def _build_regex_range(ws=True, invert=False, exclude=None):
assistant
#Here is the Python code you requested.

    """Build a range regex for a set of characters in utf8.
    This builds a valid range regex for characters in utf8 by
    iterating the entire space and building up a set of x-y ranges for
    all the characters we find which are valid.
    :param ws: should we include whitespace in this range.
    :param exclude: any characters we want to exclude
    :param invert: invert the logic
    The inversion is useful when we want to generate a set of ranges
    which is everything that\s not a certain class. For instance,
    produce all all the non printable characters as a set of ranges.
    """
    if (exclude is None):
        exclude = []
    regex = ''
    in_range = False
    last = None
    last_added = None
    def valid_char(char):
        if (char in exclude):
            result = False
        elif ws:
            result = _is_printable(char)
        else:
            result = (_is_printable(char) and (unicodedata.category(char) != 'Zs'))
        if (invert is True):
            return (not result)
        return result
    for c in _get_all_chars():
        if valid_char(c):
            if (not in_range):
                regex += re.escape(c)
                last_added = c
            in_range = True
        else:
            if (in_range and (last != last_added)):
                regex += ('-' + re.escape(last))
            in_range = False
        last = c
    else:
        if in_range:
            regex += ('-' + re.escape(c))
    return regex