Cristina Kundalini Cristina Kundalini - 1 year ago 95
Scala Question

How can I get subgroups of the match in Scala?

I have the following in python:

regex.sub(lambda t:" ", " ") +,string)

is a Regular Expression and
is a filled String.

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

Is there something similar to python function
in Scala?

Answer Source

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${}${*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 ( > 3) "$1" else "$2")
res3: String = 123 b and cc

scala> r.replaceAllIn(s, m => s"$$${ if ( > 3) 1 else 2 }")
res4: String = 123 b and cc
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download