Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do parenthesized groups work in Scala?

Tags:

regex

scala

Parentheses in regular expressions don't seem to work in match/case statements. For example, the following code

val pat1 = """ab""".r
val pat2 = """(a)(b)""".r
val pat3 = """((a)(b))""".r
val pat4 = """((a)b)""".r
val pat5 = """(ab)""".r
"ab" match {
  case pat1(x) => println("1 " + x)
  case pat2(x) => println("2 " + x)
  case pat3(x) => println("3 " + x)
  case pat4(x) => println("4 " + x)
  case pat5(x) => println("5 " + x)
  case _ => println("None of the above")
}

prints "5 ab", but I would have expected any of the patterns to match. I'd like to use "(...)?" optional elements, but I can't. Related to this, I can't get (?m) to work. My patterns work okay outside of a match/case expression. Can someone explain to me how Scala handles regular expressions in match/case expressions?

I'm trying to write a tokenizer in Scala

like image 680
David Matuszek Avatar asked Feb 18 '23 10:02

David Matuszek


1 Answers

Regex defines unapplySeq, not unapply, which means that you get each group in its own variable. Also, although lower-case matchers may work in some instances (i.e. with parameters), you really should use upper-case. So, what will work is:

val Pat1 = """ab""".r
val Pat2 = """(a)(b)""".r
val Pat3 = """((a)(b))""".r
val Pat4 = """((a)b)""".r
val Pat5 = """(ab)""".r
def no() { println("No match") }
"ab" match { case Pat1() => println("Pat1"); case _ => no }
"ab" match { case Pat2(x,y) => println("Pat2 "+x+" "+y); case _ => no }
"ab" match { case Pat3(x,y,z) => println("Pat3 "+x+" "+y+" "+z); case _ => no }
"ab" match { case Pat4(x,y) => println("Pat4 "+x+" "+y); case _ => no }
"ab" match { case Pat5(x) => println("Pat5 "+x); case _ => no }

(You will always get a match.)

If you want all matches, use @ _*

"ab" match { case Pat3(w @ _*) => println(w); case _ => no }

I'm not sure what you mean by (?a) so I don't know what's wrong with it. Don't confuse (?a) with (?:a) (or with (a?) or with (a)?).

like image 125
Rex Kerr Avatar answered Mar 02 '23 10:03

Rex Kerr