println( "TES...">

Scala regex match case directly

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 as a groovy match regex match. But I don't seem to be going to compile. What is the correct way to do this in scala?

+8
source share
2 answers

You can either match the precompiled regular expression (as in the first case below), or add an if condition. Note that usually you do not want to recompile the same regular expression for each case evaluation, but instead use it for the object.

 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 info here and some background here .

+21
source

Starting with Scala 2.13 , you can directly map a pattern to String without using a string interpolator :

 // 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") 
0
source

All Articles