The Regex
constructor takes two arguments.
new Regex(regex: String, groupNames: String*)
The groupNames
parameter is a vararg so it (they) are actually optional and, in this case, it should have been left empty because that groupNames
code is pretty useless.
Let's review what groupNames
is supposed to do. We'll start without groupNames
.
val rx = new Regex("~(A(.)C)~") // pattern with 2 groups, no group names
rx.findAllIn("~ABC~").group(0) //res0: String = ~ABC~
rx.findAllIn("~ABC~").group(1) //res1: String = ABC
rx.findAllIn("~ABC~").group(2) //res2: String = B
rx.findAllIn("~ABC~").group(3) //java.lang.IndexOutOfBoundsException: No group 3
And now with groupNames
.
val rx = new Regex("~(A(.)C)~", "x", "y", "z") // 3 groups named
rx.findAllIn("~ABC~").group("x") //res0: String = ABC
rx.findAllIn("~ABC~").group("y") //res1: String = B
rx.findAllIn("~ABC~").group("z") //java.lang.IndexOutOfBoundsException: No group 3
So why is sc.parts.tail.map(_ => "x"): _*
so useless? First because the number of names created is unrelated to the number of groups in the pattern, but also because it uses the same string, "x"
, for every name it specifies. That name will only be good for the last group named.
val rx = new Regex("~(A(.)C)~", "x", "x") // 2 groups named
rx.findAllIn("~ABC~").group("x") //res0: String = B (i.e. group(2))
...and...
val rx = new Regex("~(A(.)C)~", "x", "x", "x") // 3 groups named
rx.findAllIn("~ABC~").group("x") //java.lang.IndexOutOfBoundsException: No group 3