Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 pythonsub. However, I don't know how to get the subgroups that match.

Is there something similar to python function group in Scala?

like image 841
Cristina HG Avatar asked Oct 04 '16 19:10

Cristina HG


2 Answers

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
like image 60
som-snytt Avatar answered Sep 17 '22 17:09

som-snytt


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.

like image 44
Maroun Avatar answered Sep 17 '22 17:09

Maroun