import re


def apply_formatting(locator, args):
    """Apply formatting to the locator

    If there are no named fields in the locator this is just a simple
    call to .format. However, some locators have named fields, and we
    don't support named arguments to keep the syntax simple, so we
    need to map positional arguments to named arguments before calling
    .format.

    Example:

    Given the locator "//*[a[@title='{title}'] or
    button[@name='{title}']]//{tag}" and args of ['foo', 'bar'], we'll
    pop 'foo' and 'bar' off of the argument list and assign them to
    the kwargs keys 'title' and 'tag'.

    """
    kwargs = {}
    for match in re.finditer(r"\{([^}]+)\}", locator):
        name = match.group(1)
        if name and name not in kwargs:
            kwargs[name] = args.pop(0)
    return locator.format(*args, **kwargs)