You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter如何修改字符串中以@开头单词的文本颜色

实现以@开头单词的文本颜色修改

前端(HTML + JavaScript)

通过正则匹配目标单词,用带样式的HTML标签包裹即可:

const originalStr = "I am tagging @John at the post of @Elvin";
// 全局匹配所有@开头的单词,替换为红色样式的span标签
const coloredStr = originalStr.replace(/@(\w+)/g, '<span style="color: #ff0000;">@$1</span>');
// 将处理后的内容插入页面元素
document.getElementById("targetElement").innerHTML = coloredStr;

如果需要支持@后包含特殊字符(比如@John_Doe),可以把正则调整为@[^\s]+,匹配@后直到空格的所有内容。

Android(Kotlin)

利用SpannableString实现富文本样式:

val originalStr = "I am tagging @John at the post of @Elvin"
val spannable = SpannableString(originalStr)
val pattern = Pattern.compile("@\\w+")
val matcher = pattern.matcher(originalStr)

// 遍历所有匹配结果,设置文字颜色
while (matcher.find()) {
    val start = matcher.start()
    val end = matcher.end()
    spannable.setSpan(ForegroundColorSpan(Color.RED), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
}
// 给TextView赋值
textView.text = spannable

iOS(Swift)

通过NSAttributedString添加颜色属性:

let originalStr = "I am tagging @John at the post of @Elvin"
let attributedStr = NSMutableAttributedString(string: originalStr)
let pattern = "@\\w+"
let regex = try! NSRegularExpression(pattern: pattern)
let matches = regex.matches(in: originalStr, range: NSRange(originalStr.startIndex..., in: originalStr))

// 为每个匹配项设置红色
for match in matches {
    attributedStr.addAttribute(.foregroundColor, value: UIColor.red, range: match.range)
}
// 给UILabel设置属性文本
label.attributedText = attributedStr

通用核心逻辑

  1. 用正则表达式匹配所有以@开头的目标片段
  2. 对匹配到的文本单独应用颜色样式

内容的提问来源于stack exchange,提问作者rameez khan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 15:55:26