Reputation: 29567
I have a Scala regex that looks like:
"fizz<[a-zA-Z0-9]+,[a-zA-Z0-9]+>"
I have a method that uses this regex and compares it to a string argument. If the argument matches the regex, then I want to obtain the first matching group (that is, whatever is the value inside the first [a-zA-Z0-9]+
), as well as whatever was the second matching group. Thus, if I pass in "fizz<herp,derp>"
as my argument, I would want to be able to obtain "herp" and "derp":
def computeKey(buzz : String) : String = {
var key : String = "blah"
val regex = "fizz<[a-zA-Z0-9]+,[a-zA-Z0-9]+>".r
if(buzz matches regex) { // TODO: How do I do this check?
val firstElement : String = "" // TODO: Get this (ex: "herp")
val secondElement : String = "" // TODO: Get this (ex: "derp")
// Ex: "herp-derp"
key = s"${firstElement}-${secondElement}"
}
}
Any ideas as to how I can accomplish this?
Upvotes: 0
Views: 1907
Reputation: 14825
As @Nyavro mentioned you need parenthesis
to extract the matching parts
Apart from the pattern matching you can also do this.
val regex = "fizz<([a-zA-Z0-9]+),([a-zA-Z0-9]+)>".r
val regex(a, b) = "fizz<foo,bar>"
Scala REPL
scala> val regex = "fizz<([a-zA-Z0-9]+),([a-zA-Z0-9]+)>".r
regex: scala.util.matching.Regex = fizz<([a-zA-Z0-9]+),([a-zA-Z0-9]+)>
scala> val regex(a, b) = "fizz<foo,bar>"
a: String = foo
b: String = bar
This syntax is quite handy but be careful about the case where matching does not happen. when matching does not happen this will throw an exception. So, handle the exception in the code properly.
Upvotes: 0
Reputation: 8866
You can do it defining groups in your regexp:
val regex = "fizz<([a-zA-Z0-9]+),([a-zA-Z0-9]+)>".r
and then extracting values of the groups this way:
buzz match {
case regex(first, second) => s"$first, $second"
case _ => "blah"
}
Upvotes: 2