Expand abbreviations in a format string.

    If an abbreviation does not match a field, or matches multiple fields, it
    is left unchanged.

    Example:

        >>> fields = ("hey", "there", "dude")
        >>> expand_abbreviations("hello {d}", fields)
        'hello dude'

    Args:
        txt (str): Format string.
        fields (list of str): Fields to expand to.

    Returns:
        Expanded string.

def expand_abbreviations(txt, fields):
    """Expand abbreviations in a format string.

    If an abbreviation does not match a field, or matches multiple fields, it
    is left unchanged.

    Example:

        >>> fields = ("hey", "there", "dude")
        >>> expand_abbreviations("hello {d}", fields)
        'hello dude'

    Args:
        txt (str): Format string.
        fields (list of str): Fields to expand to.

    Returns:
        Expanded string.
    """
    def _expand(matchobj):
        s = matchobj.group("var")
        if s not in fields:
            matches = [x for x in fields if x.startswith(s)]
            if len(matches) == 1:
                s = matches[0]
        return "{%s}" % s
    return re.sub(FORMAT_VAR_REGEX, _expand, txt)