【问题标题】:Highlight text within square bracket (regex ?) Android kotlin突出显示方括号内的文本(正则表达式?)Android kotlin
【发布时间】:2020-11-11 23:10:12
【问题描述】:

我想突出显示方括号内的所有子字符串,例如:“[Toto] 正在同时 [做很多] 事情。”
我知道如何extract it
我知道如何强调:

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() 高亮被删除。

另外,高亮是用索引做的,我不想提取子字符串,而是把它放在原始字符串中,我不知道我应该通过哪种优化方式来实现。

结果如下:

【问题讨论】:

  • “但是当我执行 toString() 时,replace() 会移除高亮”——所以,不要使用toString()。尝试使用函数 on TextUtils,因为它们与 CharSequence 一起使用,并且通常保持跨度完好无损。

标签: java android regex kotlin highlight


【解决方案1】:

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

结果:

【讨论】:

  • 感谢您的帮助! ?。这正是我想要的!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-08-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多