java - 突出显示方括号内的文本(正则表达式?)Android 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
但问题是我不知道如何同时实现两者。
我显然想在应用高亮效果后删除方括号,但是当我执行 a 时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
结果:
推荐阅读
- javascript - React axios 触发一堆 get 请求
- python - 如何使用分而治之将列表分成左右两侧?
- flask-sqlalchemy - 如何在烧瓶中更新表格时保留当前图像文件
- javascript - 如何 JS 日期格式
- runtime-error - SAP Hana 存储库激活错误:找到未连接的表
- reactjs - 你如何在sequelize中传递一个json数组?
- javascript - 我可以使用 html5 中的按钮在特定元素中打开 RTE 标记吗?
- html - CSS完整性问题中的图像
- spring-boot - 定义一个抽象的 Spring 验证模型
- java - 今天我所有的Java项目都加载失败,编译器给我报错