def _resolve_datacenter(dc, pillarenv):
    '''
    If ``dc`` is a string - return it as is.

    If it's a dict then sort it in descending order by key length and try
    to use keys as RegEx patterns to match against ``pillarenv``.
    The value for matched pattern should be a string (that can use
    ``str.format`` syntax togetehr with captured variables from pattern)
    pointing to targe data center to use.

    If none patterns matched return ``None`` which meanse us datacenter of
    conencted Consul agent.
    '''
    log.debug("Resolving Consul datacenter based on: {dc}".format(dc=dc))

    try:
        mappings = dc.items()  # is it a dict?
    except __HOLE__:
        log.debug('Using pre-defined DC: {dc!r}'.format(dc=dc))
        return dc

    log.debug(
        'Selecting DC based on pillarenv using {num} pattern(s)'.format(
            num=len(mappings)
        )
    )
    log.debug('Pillarenv set to {env!r}'.format(env=pillarenv))

    # sort in reverse based on pattern length
    # but use alphabetic order within groups of patterns of same length
    sorted_mappings = sorted(mappings, key=lambda m: (-len(m[0]), m[0]))

    for pattern, target in sorted_mappings:
        match = re.match(pattern, pillarenv)
        if match:
            log.debug('Matched pattern: {pattern!r}'.format(pattern=pattern))
            result = target.format(**match.groupdict())
            log.debug('Resolved datacenter: {result!r}'.format(result=result))
            return result

    log.debug(
        'None of following patterns matched pillarenv={env}: {lst}'.format(
            env=pillarenv, lst=', '.join(repr(x) for x in mappings)
        )
    )
dataset/ETHPy150Open saltstack/salt/salt/pillar/consul_pillar.py/_resolve_datacenter