Scala中不区分大小写的模式匹配

时间:2016-12-18 17:19:39

标签: scala pattern-matching

我想在Scala中进行模式匹配,但它应该不区分大小写。有没有办法我可以编写代码而不使用单独的' case'上下案件的条款

while True:
    value = input()
    print(value)
    sys.stdout.flush()

另一种方法是提取姓氏并进行如下比较,但我有兴趣了解是否有办法在案件本身中这样做。

this.profileForm.get('title').valueChanges...

2 个答案:

答案 0 :(得分:4)

你可以使用警卫:

def main(args: Array[String]): Unit = {
  case class Person(firstName: String, lastName: String)

  val p = Person("Yuval", "Itzchakov")
  p match {
    case Person(_, lastName) if lastName.equalsIgnoreCase("itzchakov") =>
      println(s"Last name is: $lastName")
    case _ => println("Not itzchakov")
  }
}

旁注 - 案例类参数将作为val附加在声明的类上,不需要额外的赋值,也不需要val / var定义构造

答案 1 :(得分:2)

您可以使用提取器:

scala> val r = "(?i:it.*ov)".r
r: scala.util.matching.Regex = (?i:it.*ov)

scala> case class Person(firstName: String, lastName: String)
defined class Person

scala> val ps = Person("Fred", "Itchikov") :: Person("Yuval", "Itzchakov") :: Nil
ps: List[Person] = List(Person(Fred,Itchikov), Person(Yuval,Itzchakov))

scala> ps collect { case Person(_, n @ r()) => n }
res0: List[String] = List(Itchikov, Itzchakov)