Do groups in parentheses work in Scala?

Brackets in regular expressions do not 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 expected any of the patterns to match. I would like to use "(...)?" optional items, but I canโ€™t. In this regard, I can not get (? M) to work. My templates work fine outside the match / case expression. Can someone explain to me how Scala handles regular expressions in match / case expressions?

I am trying to write a tokenizer in Scala

+4
source share
2 answers

Regex defines unapplySeq , not unapply , which means that you get each group in its variable. In addition, although in some cases younger matches may work, i.e. With options, you really should use uppercase. So what will work:

 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 is wrong with him. Do not confuse (?a) with (?:a) (or with (a?) Or with (a)? ).

+8
source

Here is an example of how you can access the group(1) each match:

 val string = "one493two483three" val pattern = """two(\d+)three""".r pattern.findAllIn(string).matchData foreach { m => println(m.group(1)) } 

Check out this demo here .

0
source

Source: https://habr.com/ru/post/1447360/


All Articles