简体   繁体   中英

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM