我想在Scala中将Array of String与一个String进行模式匹配?

时间:2016-04-27 08:54:40

标签: scala

val aggFilters = Array["IR*","IR_"] 
val aggCodeVal = "IR_CS_BPV"
val flag = compareFilters(aggFilters,aggCodeVal)

根据我的要求,我想将aggFilters中给出的模式与aggCodeVal进行比较。第一种模式" IR *"与" IR_CS_BPV"匹配但不是第二个,所以我想在找到比赛后突破for循环,这样我就不会去第二个" IR _"。我不想使用像java这样的break语句。

  def compareFilters(aggFilters: Array[String], aggCodeVal: String): Boolean = {
    var flag: Boolean = false
    for (aggFilter <- aggFilters) {
      if (aggFilter.endsWith("*")
          && aggCodeVal.startsWith(aggFilter.substring(0, aggFilter.length() - 1))) {
        flag = true
      }
      else if (aggFilter.startsWith("*")
               && aggCodeVal.startsWith(aggFilter.substring(1, aggFilter.length()))) {
        flag = true
      }
      else if (((aggFilter startsWith "*")
                && aggFilter.endsWith("*"))
               && aggCodeVal.startsWith(aggFilter.substring(1, aggFilter.length() - 1))) {
        flag = true
      }
      else if (aggFilter.equals(aggCodeVal)) {
        flag = true
      }
      else {
        flag = false
      }
    }
    flag
  }

2 个答案:

答案 0 :(得分:1)

如果from setuptools import setup from setuptools.dist import Distribution DISTNAME = "packagename" DESCRIPTION = "" MAINTAINER = "" MAINTAINER_EMAIL = "" URL = "" LICENSE = "" DOWNLOAD_URL = "" VERSION = '1.2' PYTHON_VERSION = (2, 7) # Tested with wheel v0.29.0 class BinaryDistribution(Distribution): """Distribution which always forces a binary package with platform name""" def has_ext_modules(foo): return True setup(name=DISTNAME, description=DESCRIPTION, maintainer=MAINTAINER, maintainer_email=MAINTAINER_EMAIL, url=URL, license=LICENSE, download_url=DOWNLOAD_URL, version=VERSION, packages=["packagename"], # Include pre-compiled extension package_data={"packagename": ["_precompiled_extension.pyd"]}, distclass=BinaryDistribution) 是您唯一的外卡角色,您应该可以利用*进行匹配测试。

Regex

答案 1 :(得分:0)

您可以使用内置的exists方法为您完成此操作。

使用此签名提取比较单个过滤器的函数:

def compareFilter(aggFilter: String, aggCodeVal: String): Boolean 

然后:

def compareFilters(aggFilters: Array[String], aggCodeVal: String): Boolean = {
  aggFilters.exists(filter => compareFilter(filter, aggCodeVal))
}

compareFilter,BTW的实施可缩短为:

def compareFilter(aggFilter: String, aggCodeVal: String): Boolean = {
  (aggFilter.startsWith("*") && aggFilter.endsWith("*") && aggCodeVal.startsWith(aggFilter.drop(1).dropRight(1))) ||
  (aggFilter.endsWith("*") && aggCodeVal.startsWith(aggFilter.dropRight(1))) ||
  (aggFilter.startsWith("*") && aggCodeVal.startsWith(aggFilter.drop(1))) ||
  aggFilter.equals(aggCodeVal)
}

但是 - 请仔细检查一下,不确定我是否完全遵循了你的逻辑。