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.

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

3 Comments

That is definitely better than my solution
@serejja : well, potentially more efficient, and arguably more readable - maybe ;). Thanks in any case.
Many Thanks for alĺ the comments.
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
}

1 Comment

Note that it's an Array[Any] and your result is also still Any.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.