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?

Sajid
  • 891
  • 2
  • 13
  • 24

2 Answers2

25

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.

Community
  • 1
  • 1
Alex Yarmula
  • 10,477
  • 5
  • 33
  • 32
  • 3
    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! – Sajid Mar 29 '13 at 05:34
  • 3
    use `val testRegex = """TEST: (.*)""".r` and `case testRegex(m) => println("TEST "+m)` to capture the match – Renaud Nov 22 '13 at 08:55
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")
Xavier Guihot
  • 54,987
  • 21
  • 291
  • 190