JSM
JSM

Reputation: 47

How to do pattern matching on regex in a foreach function in scala?

I don't understand why this doesn't work (i have two "no match" here) :

val a = "aaa".r
val b = "bbb".r

List("aaa", "bbb").foreach {
  case a(t) => println(t)
  case b(t) => println(t)
  case _ => println("no match")
}

Upvotes: 1

Views: 492

Answers (2)

Dima
Dima

Reputation: 40510

Variable in parentheses is supposed to be capturing group. Change your regexes to val a = "(aaa)".r; val b = "(bbb)".r, that'll make it do what you want. Alternatively, change the match patterns:

List("aaa", "bbb").foreach {
   case a() => println("aaa")
   case b() => println("bbb")
   case _ => println("no match")
}

Upvotes: 4

akuiper
akuiper

Reputation: 215117

Your pattern contains no capture group, you need to put parenthesis around the pattern you want to capture in order for the the pattern matching to work:

val a = "(aaa)".r
// a: scala.util.matching.Regex = (aaa)

val b = "(bbb)".r
// b: scala.util.matching.Regex = (bbb)

List("aaa", "bbb").foreach {
   case b(t) => println(t)
   case a(t) => println(t)
   case _ => println("no match")
}

//aaa
//bbb

Upvotes: 1

Related Questions