import re


def escape_tag(tag, default="latest"):
    """
    Escapes a Docker tag, ensuring it matches the tag regular expression.
    """
    if not tag:
        return default

    tag = re.sub(r"^[^\w]", "_", tag)
    tag = re.sub(r"[^\w\.-]", "_", tag)
    return tag[0:127]