Jacek L.
Jacek L.

Reputation: 1416

Parametrized Regex for pattern matching

Is it possible to match regular expression pattern which is returned from a function? Can I do something like this?

def pattern(prefix: String) = (prefix + "_(\\w+)").r

val x = something match {
  case pattern("a")(key) => "AAAA" + key
  case pattern("b")(key) => "BBBB" + key
}

I cannot compile the above code. The following console snapshot shows an error I get. What am I doing wrong?

scala> def pattern(prefix: String) = (prefix + "_(\\w+)").r
pattern: (prefix: String)scala.util.matching.Regex

scala> def f(s:String) = s match {
     | case pattern("a")(x) => s+x+"AAAAA"
<console>:2: error: '=>' expected but '(' found.
       case pattern("a")(x) => s+x+"AAAAA"
                        ^

Upvotes: 3

Views: 243

Answers (1)

Kim Stebel
Kim Stebel

Reputation: 42037

This syntax is not supported by scala, you have to declare the extractor before you use it. See my earlier question on this topic.

Upvotes: 3

Related Questions