smeeb smeeb - 2 months ago 6
Scala Question

Extracting matching groups with Scala regex

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?

Answer

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"
}