Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala array pattern matching using regular expressions

How to pattern-match for instance the first string element in an array using regular expressions?

Consider for example

Array("col",1) match {
  case Array("""col | row""", n, _*) => n
  case _ => 0
}

which delivers 0, although the desired result would be 1.

Many Thanks.

like image 329
elm Avatar asked Mar 03 '14 12:03

elm


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.

How do you check if a string matches a regex in Scala?

Scala String matches() method with exampleThe matches() method is used to check if the string stated matches the specified regular expression in the argument or not. Return Type: It returns true if the string matches the regular expression else it returns false.

What is difference [] and () in regex?

[] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9. (a-z0-9) -- Explicit capture of a-z0-9 .


2 Answers

A Regex instance provides extractors automatically, so you can use one directly in a pattern match expression:

val regex = "col|row".r

Array("col",1) match {
  case Array(regex(), n, _*) => n
  case _ => 0
}

Also: in a more general QA about regexps in Scala, sschaef has provided a very nice string interpolation for pattern matching usage (e.g. r"col|row" in this example). A potential caveat: the interpolation creates a fresh Regex instance on every call - so, if you use the same regex a large number of times, it may more efficient to store it in a val instead (as in this answer).

like image 143
mikołak Avatar answered Oct 04 '22 11:10

mikołak


Don't know if it is the best solution, but the working one:

Array("col", 1) match {
  case Array(str: String, n, _*) if str.matches("col|row") => n //note that spaces are removed in the pattern
  case _ => 0
}
like image 30
serejja Avatar answered Oct 04 '22 12:10

serejja