gpt4 book ai didi

java - 突出显示方括号内的文本(正则表达式?)Android kotlin

转载 作者:行者123 更新时间:2023-12-02 12:40:07 33 4
gpt4 key购买 nike

我想突出显示方括号内的所有子字符串,例如:“[Toto] 同时 [做很多] 事情。”
我知道如何 extract it .
我知道如何突出显示:

val str = SpannableString("Toto is doing a lot of stuff at the same time.")
str.setSpan(BackgroundColorSpan(Color.YELLOW), 0, 4, 0)
str.setSpan(BackgroundColorSpan(Color.YELLOW), 8, 22 , 0)
textView.text = str

但问题是我不知道如何同时实现这两者。

我显然想在应用高亮效果后移除方括号,但是当我执行 toString() 然后 replace() 时,高亮被移除。

另外,高亮是用索引做的,我不想提取子串而是放在原始字符串中,我不知道应该通过哪种优化方式来实现。

结果如下: enter image description here

最佳答案

也许最好不要使用 regex 来提取右括号之间的文本。我认为这增加了这项工作的复杂性。通过对文本进行简单的迭代,我们可以获得线性复杂度的结果。

val text = "[Toto] is [doing a lot of] stuff at the same time."

val spanStack = Stack<Pair<Int, Int>>()
var index = 0

text.forEach {
when (it) {
'[' -> spanStack.push(index to index)
']' -> spanStack.push(spanStack.pop().first to index)
else -> index++
}
}

val spannableString = text
.replace("[\\[\\]]".toRegex(), "")
.let { SpannableString(it) }
.apply {
spanStack.forEach {
setSpan(
BackgroundColorSpan(Color.YELLOW),
it.first,
it.second,
SpannableString.SPAN_INCLUSIVE_INCLUSIVE
)
}
}

textView.text = spannableString

结果:

关于java - 突出显示方括号内的文本(正则表达式?)Android kotlin,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63033687/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com