Java 突出显示方括号(regex?)内的文本Android kotlin
我想强调方括号内的所有子字符串,例如:“[Toto]同时在做很多事情。”Java 突出显示方括号(regex?)内的文本Android kotlin,java,android,regex,kotlin,highlight,Java,Android,Regex,Kotlin,Highlight,我想强调方括号内的所有子字符串,例如:“[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 ,
我知道怎么做。
我知道如何强调:
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()
将删除突出显示
另外,突出显示是用索引制作的,我不想提取子字符串,而是让它进入原始字符串,我不知道应该通过哪种优化方式来实现
结果是:
也许最好不要使用
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
val text=“[Toto]同时在做很多事情。”
val spanStack=Stack()
var指数=0
text.forEach{
什么时候{
'['->spanStack.push(索引到索引)
']'->spanStack.push(spanStack.pop()。首先索引)
其他->索引++
}
}
val spannableString=文本
.replace(“[\\[\\]]”。toRegex(),“”)
.让{SpannableString(it)}
.申请{
斯潘斯塔克·弗雷奇{
固定盘(
背景色跨度(颜色为黄色),
首先,
第二,
SpannableString.SPAN_INCLUSIVE_INCLUSIVE
)
}
}
textView.text=spannableString
结果: “但是当我执行toString()时,替换()会删除突出显示”--因此,不要使用
toString()
。尝试使用函数,因为这些函数与CharSequence
一起工作,并且通常保持跨度不变。感谢您的帮助!