Ellen Spertus
02/02/2020, 8:25 PM// 1
var c = 0 // count of number of times this substitution is made in text
val newText = text.replace(re) {
c += 1
sub
}
or
// 2
val c = re.findAll(text).asSequence().count()
val newText = text.replace(re, sub)
or something better?Czar
02/02/2020, 9:11 PMval text = "abcdbdecbcd"
val matcher = "b".toPattern().matcher(text)
val sub = "Z"
var counter = 0
val newText = if(matcher.find()) {
buildString(text.length) {
do {
counter++
matcher.appendReplacement(this, sub)
} while (matcher.find())
matcher.appendTail(this)
}
} else {
text
}
// test:
check(counter == 3)
check(newText == "aZcdZdecZcd")
Ellen Spertus
02/02/2020, 9:12 PMEllen Spertus
02/02/2020, 9:15 PMStringBuilder
with StringBuffer
.Czar
02/02/2020, 9:15 PMStringBuilder
is better choice in this case.Ellen Spertus
02/02/2020, 9:16 PMCzar
02/02/2020, 9:16 PMEllen Spertus
02/02/2020, 9:16 PMCzar
02/02/2020, 9:17 PMEllen Spertus
02/02/2020, 9:17 PMEllen Spertus
02/02/2020, 9:18 PMCzar
02/02/2020, 9:19 PMEllen Spertus
02/02/2020, 9:19 PMCzar
02/02/2020, 9:20 PMre
to be a regex, or is it just a normal substring replacement?Ellen Spertus
02/02/2020, 9:21 PMc += 1
in my original code (transliterated from JS) rubbed me the wrong way because functional programming, but there’s no need to pretend I’m in a purely functional language.Ellen Spertus
02/02/2020, 9:23 PM\\b(foo|bar|baz)\\b
).Czar
02/02/2020, 9:23 PMcounter++
, but won't be as readableEllen Spertus
02/02/2020, 9:23 PMEllen Spertus
02/02/2020, 9:24 PMCzar
02/02/2020, 9:24 PMEllen Spertus
02/02/2020, 9:24 PM2
.Ellen Spertus
02/02/2020, 9:27 PMEllen Spertus
02/02/2020, 9:28 PMCzar
02/02/2020, 9:34 PMEllen Spertus
02/02/2020, 9:35 PMCzar
02/02/2020, 9:35 PMCzar
02/02/2020, 9:43 PMval text = "abcdbdecbdz"
val matcher = "(b)".toPattern().matcher(text)
val sub = "Z"
val count = matcher.results().count()
val newText = matcher.replaceAll(sub)
it's much more readable and understandable than the loop and counter var version.
The only drawback is that search is performed twice, as `replaceAll`resets the matcher state.Ellen Spertus
02/02/2020, 9:44 PMEllen Spertus
02/02/2020, 9:45 PMCzar
02/02/2020, 9:50 PMEllen Spertus
02/02/2020, 9:53 PMEllen Spertus
02/05/2020, 6:24 PMUnresolved reference: results
on the second-to-last line.Czar
02/05/2020, 6:47 PMresults()
was added in JDK9 I believeEllen Spertus
02/05/2020, 6:53 PMEllen Spertus
02/05/2020, 6:54 PMEllen Spertus
02/05/2020, 6:54 PMCzar
02/05/2020, 6:54 PM