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

如何在RichTextBox中修改多行日志的时间文本为灰色

解决RichTextBox多行日志中时间标签的着色问题

问题根源

你原来的代码依赖Lines属性逐行处理,默认每行都是独立日志条目,但多行错误日志的后续行属于同一条日志,没有时间标签;同时Split(' ')[0]在无空格的行会导致逻辑错误,最终着色失效。

解决方案

不要按行分割,而是基于<和>的位置定位时间标签——每个日志条目开头的时间块都以<起始、>结束,遍历文本找到所有符合该规则的片段,统一设置灰色即可。

实现代码

// 保存当前选中位置,避免操作后选中状态混乱
int originalSelectionStart = richTextBox1.SelectionStart;
int originalSelectionLength = richTextBox1.SelectionLength;

int currentPos = 0;
string text = richTextBox1.Text;

// 循环查找所有<开头的时间标签
while (currentPos < text.Length)
{
    int startTagIndex = text.IndexOf('<', currentPos);
    if (startTagIndex == -1) break; // 无更多标签,退出循环

    int endTagIndex = text.IndexOf('>', startTagIndex);
    if (endTagIndex == -1) break; // 找到<但未匹配到>,退出

    // 选中时间标签并设置灰色
    richTextBox1.Select(startTagIndex, endTagIndex - startTagIndex + 1);
    richTextBox1.SelectionColor = Color.Gray;

    // 移动到当前标签后方,继续查找下一个
    currentPos = endTagIndex + 1;
}

// 恢复原有选中状态
richTextBox1.Select(originalSelectionStart, originalSelectionLength);

代码说明

  • 先保存并恢复RichTextBox的选中状态,避免操作后光标位置混乱
  • 通过IndexOf循环定位所有完整的<xxx>时间标签,确保只处理有效时间块
  • 无论日志是单行还是多行,仅处理每个日志开头的时间标签,后续多行内容不会被误修改

测试验证

针对你提供的多行错误日志:

<23:0:4:320> Error-h88tzd: The source and destination are the same.
Source: 'C:\Users\user\Dropbox\PC\Desktop\...'.
Destination: 'C:\Users\user\Dropbox\PC\Desktop\....
More information: https://

代码只会将<23:0:4:320>设置为灰色,后续行内容保持原有颜色,完全符合需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 17:35:34