Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala match case on regex directly

Tags:

scala

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?

like image 917
Sajid Avatar asked Mar 29 '13 02:03

Sajid


People also ask

How do I match a pattern in regex?

Using special characters For example, to match a single "a" followed by zero or more "b" s followed by "c" , you'd use the pattern /ab*c/ : the * after "b" means "0 or more occurrences of the preceding item."

Does Scala have pattern matching?

Pattern matching is the second most widely used feature of Scala, after function values and closures. Scala provides great support for pattern matching, in processing the messages. A pattern match includes a sequence of alternatives, each starting with the keyword case.

What is Scala match case?

It is the most widely used feature in Scala. It is a technique for checking a value against a pattern. It is similar to the switch statement of Java and C. Here, “match” keyword is used instead of switch statement.

How do you use match function in Scala?

Using if expressions in case statements First, another example of how to match ranges of numbers: i match { case a if 0 to 9 contains a => println("0-9 range: " + a) case b if 10 to 19 contains b => println("10-19 range: " + b) case c if 20 to 29 contains c => println("20-29 range: " + c) case _ => println("Hmmm...") }


2 Answers

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")
like image 179
Xavier Guihot Avatar answered Oct 21 '22 15:10

Xavier Guihot


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.

like image 29
Alex Yarmula Avatar answered Oct 21 '22 13:10

Alex Yarmula