Scala 在正则表达式上直接匹配大小写

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15696595/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 05:06:55  来源:igfitidea点击:

Scala match case on regex directly

scala

提问by Sajid

I am trying to do something like the following:

我正在尝试执行以下操作:

list.foreach {x => 
     x match {
       case """TEST: .*""" => println( "TEST" )
       case """OXF.*"""   => println("XXX")
       case _             => println("NO MATCHING")
     }
}

The idea is to use it like groovy switch case regex match. But I can't seem to get to to compile. Whats the right way to do it in scala?

这个想法是像 groovy switch case regex match 一样使用它。但我似乎无法编译。在 Scala 中执行此操作的正确方法是什么?

回答by Alex Yarmula

You could either match on a precompiled regular expression (as in the first case below), or add an ifclause. Note that you typically don't want to recompile the same regular expression on each caseevaluation, but rather have it on an object.

您可以匹配预编译的正则表达式(如下面的第一种情况),也可以添加if子句。请注意,您通常不想在每次case评估时重新编译相同的正则表达式,而是将其放在一个对象上。

val list = List("Not a match", "TEST: yes", "OXFORD")
   val testRegex = """TEST: .*""".r
   list.foreach { x =>
     x match {
       case testRegex() => println( "TEST" )
       case s if s.matches("""OXF.*""") => println("XXX")
       case _ => println("NO MATCHING")
     }
   }

See more information hereand some background here.

在此处查看更多信息,在此处查看一些背景信息

回答by Xavier Guihot

Starting Scala 2.13, it's possible to directly pattern match a Stringby unapplying a string interpolator:

开始Scala 2.13,可以String通过不应用字符串插值器直接模式匹配 a :

// val examples = List("Not a match", "TEST: yes", "OXFORD")
examples.map {
  case s"TEST: $x" => x
  case s"OXF$x"    => x
  case _           => ""
}
// List[String] = List("", "yes", "ORD")