import re


def format_unit(unit):
    """
    Format a string with units to LaTeX format

    Parameters
    ----------
    unit : str
        String containing units.
    """
    # Define regex pattern for units as alphabetic characters followed by
    # a positive or negative int.
    unit_pattern = r"^[a-zA-Z]+-?(\d+)?$"
    # Get each unit from the passed string
    splits = unit.strip().split()
    # Generate the LaTeX units
    units = []
    for split in splits:
        # Check if the passed unit has the valid format
        if not re.match(unit_pattern, split):
            raise ValueError("Invalid unit '{}'.".format(split))
        # Take the alphabetic characters of the unit and its power (if exists)
        alpha = re.findall("[a-zA-Z]+", split)[0]
        power = re.findall(r"-?\d+", split)
        # Build LaTeX unit
        unit_tex = r"\text{{{}}}".format(alpha)
        if power:
            unit_tex += "^{{{}}}".format(power[0])
        units.append(unit_tex)
    return r" ".join(units)