0

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!!!.

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

That is my great privilege and pleasure.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.