String.replaceAll variant that handles each match using closure

This commit is contained in:
Sergey Mashkov
2013-10-03 09:40:32 +04:00
committed by Evgeny Gerashchenko
parent c943b4e9d5
commit 391c892a21
2 changed files with 59 additions and 0 deletions
+26
View File
@@ -524,3 +524,29 @@ public inline fun String.trimTrailing(): String {
}
return if (count < this.length) substring(0, count) else this
}
/**
* Replaces every *regexp* occurence in the text with the value retruned by the given function *body* that can handle
* particular occurance using [[MatchResult]] provided.
*/
public fun String.replaceAll(regexp: String, body: (java.util.regex.MatchResult) -> String) : String {
val sb = StringBuilder(this.length())
val p = regexp.toRegex()
val m = p.matcher(this)
var lastIdx = 0
while (m.find()) {
sb.append(this, lastIdx, m.start())
sb.append(body(m.toMatchResult()))
lastIdx = m.end()
}
if (lastIdx == 0) {
return this;
}
sb.append(this, lastIdx, this.length())
return sb.toString()
}