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.
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."
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.
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.
[] 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 .
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).
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With