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:
- python - subn(count=3)
- php - preg_replace(limit=3)
- rust - regex.replacen
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
Post a Comment