import re


def correct_tag(tag: str, prefix: str = "#") -> str:
    """Attempts to correct malformed Clash of Clans tags
    to match how they are formatted in game

    Example
    -------

    .. code-block:: python3

            new_tag = utils.correct_tag(" 123aBc O")
            # new_tag is "#123ABC0".


    Parameters
    ----------
    tag: str
        The tag to correct.
    prefix: str
        The prefix to insert at the start of the tag. Defaults to ``#``.

    Returns
    -------
    str
        The corrected tag.
    """
    return tag and prefix + re.sub(r"[^A-Z0-9]+", "", tag.upper()).replace("O", "0")