Ito*_*oun 3 java regex android highlight kotlin
我想突出显示方括号内的所有子字符串,例如:“[Toto] 同时[做很多]事情。”
我知道如何提取它。
我知道如何突出显示:
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
Run Code Online (Sandbox Code Playgroud)
但问题是我不知道如何同时实现两者。
我显然想在应用突出显示效果后删除方括号,但是当我执行 atoString()然后 a 时,replace()突出显示会被删除。
另外,突出显示是用索引制作的,我不想提取子字符串而是将其放入原始字符串中,我不知道应该通过哪种优化方式来实现这一点。
也许最好不要使用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
Run Code Online (Sandbox Code Playgroud)
结果:
| 归档时间: |
|
| 查看次数: |
840 次 |
| 最近记录: |