Search code examples
regexscalapattern-matchingextractor

Problems with scala regex extractor


I have a problem with the regex extrator, this is my regex

val regex = """(some\/params\/results\/\b[A-Z]{3}\/[A-Z]{3}\b\/)*""".r

And when I try to do this:

val regex(res) = "some/params/results/XXX/YYY/2016-05-09/2016-05-18/1/0/0"

I get an:

some/params/results/XXX/YYY/2016-05-09/2016-05-18/1/0/0 (of class java.lang.String)
scala.MatchError: some/params/results/XXX/YYY/2016-05-09/2016-05-18/1/0/0 (of class java.lang.String)

I would like to use it in pattern matching like this:

url match {
  case regex(res) => res
  case _ => url
}

to extract the group some/params/results/XXX/YYY/


Solution

  • Add penultimate element dot . before *

    Explanation:

    (...)* - star at the end means: zero or more matches of content in the brackets.

    (...).* - star at the end means: zero or more matches of ., where . is any single character.