Compile a regular hexpression (a short form regular expression subset
    specifically designed for searching for binary strings).

    A regular hexpression consists of hex tuples interspaced with control
    characters. The available control characters are:

    - ``?``: Any byte (optional).
    - ``.``: Any byte (required).
    - ``?{n}``: A set of 0 up to *n* bytes.
    - ``.{n}``: A set of exactly *n* bytes.
    - ``*``: Any number of bytes (or no bytes at all).
    - ``+``: Any number of bytes (at least one byte).

    Args:
        pattern(str): The reghex pattern.

    Returns:
        regexp: A regular expression as returned by ``re.compile()``.

def reghex(pattern):
    """
    Compile a regular hexpression (a short form regular expression subset
    specifically designed for searching for binary strings).

    A regular hexpression consists of hex tuples interspaced with control
    characters. The available control characters are:

    - ``?``: Any byte (optional).
    - ``.``: Any byte (required).
    - ``?{n}``: A set of 0 up to *n* bytes.
    - ``.{n}``: A set of exactly *n* bytes.
    - ``*``: Any number of bytes (or no bytes at all).
    - ``+``: Any number of bytes (at least one byte).

    Args:
        pattern(str): The reghex pattern.

    Returns:
        regexp: A regular expression as returned by ``re.compile()``.
    """

    if not reghex_check.match(pattern):
        raise SyntaxError('Invalid reghex pattern.')

    b_pattern = b''

    for match in reghex_regex.finditer(pattern):
        _, match_hex, _, match_char, match_char_len, match_star_plus = match.groups()
        if match_hex:
            b_pattern += re.escape(pwnypack.codec.dehex(match_hex))
        elif match_char:
            if match_char == '?':
                if match_char_len is None:
                    b_pattern += b'.?'
                else:
                    b_pattern += ('.{0,%d}?' % int(match_char_len[1:-1])).encode('ascii')
            else:
                if match_char_len is None:
                    b_pattern += b'.'
                else:
                    b_pattern += b'.' * int(match_char_len[1:-1])
        elif match_star_plus:
            b_pattern += b'.' + match_star_plus.encode('ascii') + b'?'

    try:
        return re.compile(b_pattern)
    except (TypeError, binascii.Error, re.error):
        raise SyntaxError('Invalid reghex pattern.')