winforms 如何在RichTextBox中选择两个字符之间的文本

w8biq8rn  于 2022-11-16  发布在  其他
关注(0)|答案(3)|浏览(105)

我有一个RichTextBox,它可以记录有关我的应用程序的信息。下面是它可能记录的内容的示例:

<22:52:21:179> Starting Argo Studio
<22:52:22:731> Argo Studio has finished starting
<22:52:30:41> Time to load commands: 00:00:00.00
<22:52:30:48> Created 'App 1'

<>之间的文本是时间。
"我需要将时间的颜色改为灰色“
以前,我这样做:

for (int i = 0; i < RichTextBox.Lines.Length; i++)
{
    int indexStart = RichTextBox.GetFirstCharIndexFromLine(i);
    int indexEnd = RichTextBox.Lines[i].Split(' ')[0].Length;
    RichTextBox.Select(indexStart, indexEnd);
    RichTextBox.SelectionColor = Color.Gray;
}

但是,这对我不再有效,因为现在我有多行日志:

<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://
qnzebej0

qnzebej01#

如果> or <不存在,您可以跳过这一行。请尝试以下操作:

RichTextBox.AppendText("< 22:52:21:179 > Starting Argo Studio" +
       "\r\n" + "<22:52:22:731 > Argo Studio has finished starting" +
       "\r\n" + "<22:52:30:41 > Time to load commands: 00:00:00.00" +
       "\r\n" + "< 22:52:30:48 > Created 'App 1'" +
       "\r\n" + "23:0:4:320 Error - h88tzd: The source and destination are the same." +
       "\r\n" + @"Source: 'C:\Users\user\Dropbox\PC\Desktop\...'." +
       "\r\n" + @"Destination: 'C:\Users\user\Dropbox\PC\Desktop\...." +
       "\r\n" + "More information: https:/");

        for (int i = 0; i < RichTextBox.Lines.Length; i++)
        {
            int indexStart = RichTextBox.Lines[i].IndexOf("<");
            int indexEnd = RichTextBox.Lines[i].LastIndexOf(">");
            if (indexStart < 0 || indexEnd < 0)
                continue;
            int baseIndex = RichTextBox.Text.IndexOf(RichTextBox.Lines[i]);
            RichTextBox.Find(RichTextBox.Lines[i].Substring(indexStart+1, indexEnd-1));
            RichTextBox.SelectionColor = Color.Gray;
        }

则结果为:

希望这对你有帮助!

syqv5f0l

syqv5f0l2#

仅当行包含<>时,才格式化颜色

for (int i = 0; i < RichTextBox.Lines.Length; i++)
{
    if (RichTextBox.Lines[i].Contains("<") && 
        RichTextBox.Lines[i].Contains(">"))
    {
        int indexStart = RichTextBox.GetFirstCharIndexFromLine(i);
        int indexEnd = RichTextBox.Lines[i].Split(' ')[0].Length;
        RichTextBox.Select(indexStart, indexEnd);
        RichTextBox.SelectionColor = Color.Gray;
    }
}
toiithl6

toiithl63#

您可以使用Regex.Matches来查找与时间戳匹配的文本的所有部分。
每个Match对象会传回找到相符项目的字符Index,以及相符字串的Length
该信息可用于执行选择。
文本是否换行无关紧要,因为考虑的是整个文本。
例如:

var matches = Regex.Matches(richTextBox.Text, @"<*\d+:\d+:\d+:\d+>*", RegexOptions.Multiline);
foreach (Match m in matches) {
    richTextBox.SelectionStart = m.Index;
    richTextBox.SelectionLength = m.Length;
    richTextBox.SelectionColor = Color.Gray;
}

不清楚是否要在此处选择时间戳:

Time to load commands: 00:00:00.00

如果这样做,则需要进行少量更改(例如,将模式设置为<*\d+:\d+:\d+[:.]\d+>*
如果只需要尖括号中的时间戳,则<\d+:\d+:\d+:\d+>

相关问题