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

基于匹配模式实现RichTextBox文本高亮着色的问题求助

RichTextBox按标签着色时索引计算错误

我尝试实现一个支持着色的RichTextBox,用{颜色名}作为后续文本的颜色标记。比如示例文本:
Hey, This{Red} IS A {Cyan}sample. The {Green}color is green color
预期显示效果:

  • "Hey, This " 使用默认颜色
  • "IS A" 显示红色
  • "sample. The " 显示青色
  • "color is green color" 显示绿色

但RichTextBox最终显示的文本不含这些{颜色名}标签,导致我计算文本索引和长度时出错,着色位置完全错误。以下是我的代码和错误效果截图:

// 原始文本:Hey, This{Red} IS A {Cyan}sample. The {Green}color is green color
// 预期显示文本:Hey, This IS A sample. The color is green color

const string OriginalText = "Hey, This{Red} IS A {Cyan}sample. The {Green}color is green color";
const string ShownText = "Hey, This IS A sample. The color is green color";
const string Pattern = "(?<=\\{)(.*?)(?=\\})";

rtbMain.Text = ShownText;

rtbMain.SelectAll();
rtbMain.SelectionColor = Color.Black;
rtbMain.SelectionBackColor = Color.White;
Regex regex = new(Pattern, RegexOptions.IgnoreCase);
MatchCollection matches = regex.Matches(OriginalText);

if (matches.Count > 0)
{
    var rtbText = rtbMain.Text;
    var length = ShownText.Length;
    var allMatches = new List<Match>();

    for (int i = 0; i < matches.Count; i++)
    {
        var m = matches[i];
        allMatches.Add(m);
        Match nextMatch = null;
        if (matches.Count > i + 1)
        {
            nextMatch = matches[i + 1];
        }
        var sum = GetSum();
        var start = m.Index;
        var currentLength = m.Length;
        if (nextMatch != null)
        {
            var end = nextMatch.Index - start- sum;
            rtbMain.Select(start- 1, end);
        }
        else
        {
            var currentIndex = OriginalText.IndexOf(m.Value);
            rtbMain.Select(length - currentIndex, (length - currentIndex) - sum);
        }
        rtbMain.SelectionColor = GetColor(m.Value);
    }
    int GetSum()
    {
        return allMatches!.Select(m => m.Value.Length - 1).Sum();
    }
    Color GetColor(string color)
    {
        return Color.FromName(color);
    }
}
else
{
    Debug.WriteLine("No matches found");
}

错误着色效果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 15:10:42