簡體   English   中英

突出顯示 RichTextBox 控件中的文本

[英]Highlight text in a RichTextBox Control

我試圖在 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數組中指定的所有字符串值,並且不會每次都發生。

例子:

在此處輸入圖片說明

在此處輸入圖片說明

我不確定為什么有些行被跳過而有些則沒有。

如果您不反對簡單的 Regex 方法,您可以使用Regex.Matches將您的短語列表與 RichTextBox 的文本進行匹配。
Matches 集合中的每個Match都包含找到匹配的索引(文本內的位置)和它的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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM