0

So, how to do that in groovy (or java)? I look for something like this:

someString.replaceN(/(?<=\p{L}) (?=\p{L})/, '', 3) // replace first 3 matches

For now, I only came to this stupid solution:

(0..2).each { s = s.replaceFirst(/(?<=\p{L}) (?=\p{L})/, '') }

In other languages it's easy as pie:

AndreyT
  • 1,389
  • 12
  • 25

1 Answers1

2

I think what you are after is

3.times { s = s.replaceFirst(/(?<=\p{L}) (?=\p{L})/, '') }

Or if you need it more often you can also easily add the method to String class like

String.metaClass.replace << { pattern, replacement, n ->
    def result = delegate
    n.times { result = result.replaceFirst pattern, replacement }
    result
}

someString.replace(/(?<=\p{L}) (?=\p{L})/, '', 3)
Vampire
  • 32,892
  • 3
  • 65
  • 94