def termcap_distance(ucs, cap, unit, term):
    """termcap_distance(S, cap, unit, term) -> int

    Match horizontal distance by simple ``cap`` capability name, ``cub1`` or
    ``cuf1``, with string matching the sequences identified by Terminal
    instance ``term`` and a distance of ``unit`` *1* or *-1*, for right and
    left, respectively.

    Otherwise, by regular expression (using dynamic regular expressions built
    using ``cub(n)`` and ``cuf(n)``. Failing that, any of the standard SGR
    sequences (``\033[C``, ``\033[D``, ``\033[nC``, ``\033[nD``).

    Returns 0 if unmatched.
    """
    assert cap in ('cuf', 'cub')
    # match cub1(left), cuf1(right)
    one = getattr(term, '_%s1' % (cap,))
    if one and ucs.startswith(one):
        return unit

    # match cub(n), cuf(n) using regular expressions
    re_pattern = getattr(term, '_re_%s' % (cap,))
    _dist = re_pattern and re_pattern.match(ucs)
    if _dist:
        return unit * int(_dist.group(1))

    return 0