java - How to replace N-number of matches in the string? -


this question has answer here:

so, how in groovy (or java)? this:

somestring.replacen(/(?<=\p{l}) (?=\p{l})/, '', 3) // replace first 3 matches 

for now, came stupid solution:

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

in other languages it's easy pie:

i think after is

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

or if need more can add method 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) 

Comments

Popular posts from this blog

serialization - Convert Any type in scala to Array[Byte] and back -

matplotlib support failed in PyCharm on OSX -

python - Matplotlib: TypeError: 'AxesSubplot' object is not callable -