突出显示RichTextBox控件中的文本

问题描述

我正在尝试突出显示RichTextBox中多行特定文本。
这是我突出显示文本的代码:

public void HighlightMistakes(RichTextBox richTextBox)
{
    string[] phrases =  { "Drivers Do Not Match","Current Does Not Match","No Drivers Found" };      
    foreach (var phrase in phrases)
    {
        int startIndex = 0;
        while (startIndex <= richTextBox.TextLength)
        {
            int phraseStartIndex = richTextBox.Find(phrase,startIndex,RichTextBoxFinds.None);
            if (phraseStartIndex != -1)
            {
                richTextBox.SelectionStart = phraseStartIndex;
                richTextBox.SelectionLength = phrase.Length;
                richTextBox.SelectionBackColor = Color.Yellow;
            }
            else break;
            startIndex += phraseStartIndex + phrase.Length;
        }
    }
}  

这是我向RTB添加文本并调用上面的函数的方式:

foreach (var a in resultList)
{
    richTextBox1.AppendText("\n"+a + "\n");
    HighlightMistakes(richTextBox1);
}

但是,HighlightMistakes不能按我希望的方式工作。这样做的目的是突出显示phrases数组中指定的所有字符串值,而并非每次都这样。

示例:

enter image description here

enter image description here

我不确定为什么跳过了某些行而没有跳过某些行。

解决方法

如果对简单的Regex方法没有任何帮助,则可以使用Regex.Matches将短语列表与RichTextBox的文本进行匹配。
匹配项集合中的每个Match都包含找到匹配项的Index(文本内的位置)及其Length,因此您只需调用.Select(Index,Length)即可选择一个短语并将其突出显示。
所使用的模式是将短语与管道(|相匹配而产生的字符串。
由于文本中可能包含元字符,因此每个短语都传递给Regex.Escape()

如果要考虑这种情况,请删除RegexOptions.IgnoreCase

using System.Text.RegularExpressions;

string[] phrases = { "Drivers Do Not Match","Current Does Not Match","No Drivers Found" };
HighlightMistakes(richTextBox1,phrases);

private void HighlightMistakes(RichTextBox rtb,string[] phrases)
{
    ClearMistakes(rtb);
    string pattern = string.Join("|",phrases.Select(phr => Regex.Escape(phr)));

    var matches = Regex.Matches(rtb.Text,pattern,RegexOptions.IgnoreCase);
    foreach (Match m in matches) {
        rtb.Select(m.Index,m.Length);
        rtb.SelectionBackColor = Color.Yellow;
    }
}

private void ClearMistakes(RichTextBox rtb)
{
    int selStart = rtb.SelectionStart;
    rtb.SelectAll();
    rtb.SelectionBackColor = rtb.BackColor;
    rtb.SelectionStart = selStart;
    rtb.SelectionLength = 0;
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...