andrewJhonq
andrewJhonq

Reputation: 221

how use replaceAllIn in a scala regex only replacing capturing match

sorry if the title is not clear, I'm open to change it if you suggest a better one, the problem is it:

I've a string like this

val text1 = "123 456 blah 345qq"

and this code

val rx1 = """(\d+)\s+\d+""" .r
def something(a : String) = s"<:$a:>"
rx1.replaceAllIn(text1,(m)=> something(???))

I just wanna replace the capturing match between parenthesis, that means, the result must be

 <:123:> 456 blah 345qq

using

  rx1.replaceAllIn(text1,(m)=> something(m) 

capture the whole match: not only the first digits also the space(s) and next digit(s) resulting in something like this <:123 456:> blah 345qq so I know than I must use the group method in the regex.Match

rx1.replaceAllIn(text1,(m)=> something(m.group(1)))

this is a bit better but the result is <:123:> blah 345qq , notice than the digits 456 are removed

<:123:> blah 345qq wrong!
<:123:> 456 blah 345qq right

how can archieve this goal in a nice and scala idiomatic way?..thanks!!!.

Upvotes: 0

Views: 622

Answers (1)

som-snytt
som-snytt

Reputation: 39577

There is API to do it:

scala> r.replaceAllIn(text, m => s"${f(m group 1)}${m.matched.substring(m end 1)}")
res2: String = <:123:> 456 blah 345qq

You could work harder to insert whatever was matched in front of group 1, depending on the pattern.

For following along at home:

scala> val text = "123 456 blah 345qq"
text: String = 123 456 blah 345qq

scala> val r = """(\d+)\s+\d+""" .r
r: scala.util.matching.Regex = (\d+)\s+\d+

scala> def f(s: String) = s"<:$s:>"
f: (s: String)String

Upvotes: 1

Related Questions