加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – 字符串不区分大小写的模式匹配

发布时间:2020-12-16 09:16:22 所属栏目:安全 来源:网络整理
导读:match (str) { case "String1" = ??? case "String2" = ???} 这是区分大小写的匹配.如何编写不区分大小写的匹配?我知道我可以调用每个分支的LowerCase,但是我想要更优雅的解决方案. 解决方法 基本方法: 您可以使用模式守卫和正则表达式 str match {case s
match (str) {
  case "String1" => ???
  case "String2" => ???
}

这是区分大小写的匹配.如何编写不区分大小写的匹配?我知道我可以调用每个分支的LowerCase,但是我想要更优雅的解决方案.

解决方法

基本方法:

您可以使用模式守卫和正则表达式

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读