match (str) {
case "String1" => ???
case "String2" => ???
}
这是区分大小写的匹配。如何编写不区分大小写的匹配?我知道我可以为每个分支调用toLowerCase,但我想要更优雅的解决方案。
答案 0 :(得分:22)
基本方法:
您可以使用模式警卫和正则表达式
str match {
case s if s matches "(?i)String1" => 1
case s if s matches "(?i)String2" => 2
case _ => 0
}
复杂的方法:
使用字符串插值和正则表达式隐含
implicit class CaseInsensitiveRegex(sc: StringContext) {
def ci = ( "(?i)" + sc.parts.mkString ).r
}
def doStringMatch(str: String) = str match {
case ci"String1" => 1
case ci"String2" => 2
case _ => 0
}
REPL中的一些示例用法:
scala> doStringMatch("StRINg1")
res5: Int = 1
scala> doStringMatch("sTring2")
res8: Int = 2
答案 1 :(得分:5)
另一种不依赖于正则表达式或插值符的方法:
implicit class StringExtensions(val s: String) extends AnyVal {
def insensitive = new {
def unapply(other: String) = s.equalsIgnoreCase(other)
}
}
val test1 = "Bye".insensitive
val test2 = "HELLo".insensitive
"Hello" match {
case test1() => println("bad!")
case test2() => println("sweet!")
case _ => println("fail!")
}
这是使用插值器的另一种方法,但没有正则表达式:
implicit class StringInterpolations(sc: StringContext) {
def ci = new {
def unapply(other: String) = sc.parts.mkString.equalsIgnoreCase(other)
}
}
"Hello" match {
case ci"Bye" => println("bad!")
case ci"HELLO" => println("sweet!")
case _ => println("fail!")
}
上述内容也可以用于模式匹配案例类,例如:
case class Dog(name: String)
val fido = Dog("FIDO")
fido match {
case Dog(ci"fido") => "woof"
case _ => "meow :("
}
答案 2 :(得分:3)
简易解决方案:
val str = "string1"
str toUpperCase match (str) {
case "STRING1" => ???
case "STRING2" => ???
}