Cristina Kundalini Cristina Kundalini - 2 months ago 10
Scala Question

How can I get subgroups of the match in Scala?

I have the following in python:

regex.sub(lambda t: t.group(1).replace(" ", " ") + t.group(2),string)


where
regex
is a Regular Expression and
string
is a filled String.

So I am trying to do the same in Scala, using
regex.replaceAllIn(...)
function instead of python
sub
. However, I don't know how to get the subgroups that match.

Is there something similar to python function
group
in Scala?

Answer

The scaladoc has one example. Provide a function from Match instead of a string.

scala> val r = "a(b)(c)+".r
r: scala.util.matching.Regex = a(b)(c)+

scala> val s = "123 abcccc and abcc"
s: String = 123 abcccc and abcc

scala> r.replaceAllIn(s, m => s"a${m.group(1).toUpperCase}${m.group(2)*3}")
res0: String = 123 aBccc and aBccc

The resulting string also does group substitution.

scala> val r = "a(b)(c+)".r
r: scala.util.matching.Regex = a(b)(c+)

scala> r.replaceAllIn(s, m => if (m.group(2).length > 3) "$1" else "$2")
res3: String = 123 b and cc

scala> r.replaceAllIn(s, m => s"$$${ if (m.group(2).length > 3) 1 else 2 }")
res4: String = 123 b and cc
Comments