Skip to content

Instantly share code, notes, and snippets.

@kaja47
Last active February 15, 2018 18:44
Show Gist options
  • Save kaja47/f1804142577495beae13041c9d9094d8 to your computer and use it in GitHub Desktop.
Save kaja47/f1804142577495beae13041c9d9094d8 to your computer and use it in GitHub Desktop.
reasonable replaceAll
import scala.util.matching.Regex
import java.util.regex.Matcher
def replaceAllByString(r: Regex, s: String, f: Matcher => String) = {
val m = r.pattern.matcher(s)
m.reset()
var lastAppendPos = 0
var result = m.find()
if (result) {
val sb = new java.lang.StringBuilder(s.length)
do {
sb.append(s, lastAppendPos, m.start())
//sb.append(f(new Regex.Match(s, m, Seq()).force))
sb.append(f(m))
lastAppendPos = m.end()
result = m.find()
} while (result)
//appendTail(sb);
sb.append(s, lastAppendPos, s.length)
sb.toString
} else {
s
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment