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 pythonsub
. However, I don't know how to get the subgroups that match.
Is there something similar to python function group
in Scala?
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
You can use replaceAll
, and use $n
, where "n" is the group you want to match. For example:
yourString.replaceAll(yourRegex, "$1")
Replaces the matched parts with the first group.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With