Scala match case on regex directly

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")

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.

Tags:

Scala