smeeb smeeb - 1 year ago 76
Scala Question

Extracting matching groups with Scala regex

I have a Scala regex that looks like:


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
), as well as whatever was the second matching group. Thus, if I pass in
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 Source

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"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download