match (str) {
case "String1" => ???
case "String2" => ???
}
Run Code Online (Sandbox Code Playgroud)
这是区分大小写的匹配.如何编写不区分大小写的匹配?我知道我可以为每个分支调用toLowerCase,但我想要更优雅的解决方案.
And*_*ann 22
基本方法:
您可以使用Pattern Guards和Regular Expressions
str match {
case s if s matches "(?i)String1" => 1
case s if s matches "(?i)String2" => 2
case _ => 0
}
Run Code Online (Sandbox Code Playgroud)
复杂的方法:
使用字符串插值和正则表达式进行隐含
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
}
Run Code Online (Sandbox Code Playgroud)
REPL中的一些示例用法:
scala> doStringMatch("StRINg1")
res5: Int = 1
scala> doStringMatch("sTring2")
res8: Int = 2
Run Code Online (Sandbox Code Playgroud)
另一种不依赖于正则表达式或插值符的方法:
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!")
}
Run Code Online (Sandbox Code Playgroud)
这是使用插值器但没有正则表达式的另一种方法:
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!")
}
Run Code Online (Sandbox Code Playgroud)
以上内容也可用于模式匹配案例类,例如:
case class Dog(name: String)
val fido = Dog("FIDO")
fido match {
case Dog(ci"fido") => "woof"
case _ => "meow :("
}
Run Code Online (Sandbox Code Playgroud)
简单的解决方案:
val str = "string1"
str toUpperCase match (str) {
case "STRING1" => ???
case "STRING2" => ???
}
Run Code Online (Sandbox Code Playgroud)