字符串不区分大小写的模式匹配 [英] Case insensitive pattern matching for strings
本文介绍了字符串不区分大小写的模式匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
match (str) {
case "String1" => ???
case "String2" => ???
}
这是区分大小写的匹配.如何编写不区分大小写的匹配?我知道我可以为每个分支调用 toLowerCase,但我想要更优雅的解决方案.
This is case sensitive matching. How to write case insensitive matching? I know I can call toLowerCase for each branch, but I want more elegant solution.
推荐答案
基本方法:
您可以使用模式保护和正则表达式
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 中的一些示例用法:
Some example usage in the REPL:
scala> doStringMatch("StRINg1")
res5: Int = 1
scala> doStringMatch("sTring2")
res8: Int = 2
这篇关于字符串不区分大小写的模式匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文