英文:
Highlight text within square bracket (regex ?) Android kotlin
问题
我想突出显示所有位于方括号内的子字符串,例如:“[Toto] is [doing a lot of] stuff at the same time。”
我知道如何提取它。
我知道如何突出显示:
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()
时,高亮效果被移除。
另外,高亮是基于索引的,我不想提取子字符串,而是保留在原始字符串中,我不知道应该通过哪种优化的方式来实现这一点。
英文:
I would like to highlight all of the substring which are inside square brackets, ex: "[Toto] is [doing a lot of] stuff at the same time."
I know how to extract it.
I know how to highlight:
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
But the problem is I don't know how to achieve both together.
I obviously want to remove the square bracket after have applied the highlight effect but when I do a toString()
then a replace()
the highlight is removed.
Also, the highlight is made with index, and I don't want to extract the substring but let it in the original string, I don't know by which optimized way I should achieve that.
答案1
得分: 4
也许最好不使用 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
结果:
<tr>
<td><img src="https://i.stack.imgur.com/xDdRE.png" width="300"/></td>
</tr>
英文:
Maybe it's better not to use regex
in order to extract the texts between close brackets. I think it increases the complexity of this job. Using a simple iteration over the text, we can achieve the result in linear complexity.
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
<br/>
Result:
<tr>
<td><img src="https://i.stack.imgur.com/xDdRE.png" width="300"/></td>
</tr>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论