code: 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: %s', dc)
      try:
          mappings = dc.items()
      except AttributeError:
          log.debug('Using pre-defined DC: \'%s\'', dc)
          return dc
      log.debug('Selecting DC based on pillarenv using %d pattern(s)', len(mappings))
      log.debug('Pillarenv set to \'%s\'', pillarenv)
      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: \'%s\'', pattern)
              result = target.format(**match.groupdict())
              log.debug('Resolved datacenter: \'%s\'', result)
              return result
      log.debug(
          'None of following patterns matched pillarenv=%s: %s',
          pillarenv, ', '.join(repr(x) for x in mappings)
      )