Hi, is there a way to replace some content in the ...
# compose-android
a
Hi, is there a way to replace some content in the
AnnotatedString
with the replacement string in such a way that replace method returns
AnnotatedString
string itself?
In my string I have placeholder
%PLACEHOLDER%
string which I want to replace at single place with some other actual value of placeholder
m
Maybe this:
Copy code
fun CharSequence.replaceAnnotated(
    regex: Regex,
    transform: (MatchResult) -> AnnotatedString?,
): AnnotatedString {
    val input = this
    var offset = 0
    return buildAnnotatedString {
        regex.findAll(input).forEach { mr ->
            val replacement = transform(mr) ?: return@forEach
            val first = mr.range.first
            if (first > offset) {
                append(input.subSequence(offset, first))
            }
            append(replacement)
            offset = mr.range.last + 1
        }
        if (offset < input.length) {
            append(input.subSequence(offset, input.length))
        }
    }
}
thank you color 1
178 Views