首页 > 解决方案 > 突出显示方括号内的文本(正则表达式?)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()高亮被删除。

另外,突出显示是用索引制作的,我不想提取子字符串,而是让它在原始字符串中,我不知道我应该通过哪种优化方式来实现这一点。

结果是: 在此处输入图像描述

标签: javaandroidregexkotlinhighlight

解决方案


也许最好不要使用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

结果:


推荐阅读