10

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?

2 Answers 2

27

You could either match on a precompiled regular expression (as in the first case below), or add an if clause. Note that you typically don't want to recompile the same regular expression on each case evaluation, but rather have it on an 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 information here and some background here.

Sign up to request clarification or add additional context in comments.

2 Comments

I wish scala added more syntactic sugar for handling this, I don't like the extra codes for matching simpler regex. After spending quite some time to find out how to do it, I couldn't believe its not doable in Scala hence the StackOverflow post!
use val testRegex = """TEST: (.*)""".r and case testRegex(m) => println("TEST "+m) to capture the match
12

Starting Scala 2.13, it's possible to directly pattern match a String by unapplying 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")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.