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
Scala match case on regex directly
提问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")
}
}
回答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")

