5

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.

elm
  • 20,117
  • 14
  • 67
  • 113

2 Answers2

7

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

Community
  • 1
  • 1
mikołak
  • 9,605
  • 1
  • 48
  • 70
2

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
}
serejja
  • 22,901
  • 6
  • 64
  • 72