Search And Highlight Multiple Text

时间:2015-07-28 16:42:31

标签: c# search text

Here is the code I have, It works great, but what I need it to do is search for more than one word and highlight all the words from the list I give it.

So lets say I have it search "Close" and it highlights all the words containing that Red. Well how do I make it so it will highlight more words other than just "Close". So have it simultaneously search multiple text such as "Close" && "Enter" && "Leave"


private void btn_Search_Click(object sender, EventArgs e)
{
    try
    {
        if (richTextBox1.Text != string.Empty)
        {
            // if the ritchtextbox is not empty; highlight the search criteria
            int index = 0;
            String temp = richTextBox1.Text;
            richTextBox1.Text = "";
            richTextBox1.Text = temp;
            while (index < richTextBox1.Text.LastIndexOf("Close"))
            {
                richTextBox1.Find("Close", index, richTextBox1.TextLength, RichTextBoxFinds.None);
                richTextBox1.SelectionColor = Color.Cyan;
                index = richTextBox1.Text.IndexOf("Close", index) + 1;
                richTextBox1.Select();
            }
        }
    }
}

2 个答案:

答案 0 :(得分:0)

This worked for me:

// using System.Text.RegularExpressions;

string[] searchTerms = new[] { "Close", "Enter", "Leave" };

// if the richtextbox is not empty; highlight the search criteria
if (richTextBox1.Text != string.Empty)
{
    // reset the selection
    string text = richTextBox1.Text;
    richTextBox1.Text = "";
    richTextBox1.Text = text;
    // find all matches
    foreach (Match m in new Regex(string.Join("|", searchTerms.Select(t => t.Replace("|", "\\|")))).Matches(richTextBox1.Text))
    {
        // for each match, select and then set the color
        richTextBox1.Select(m.Index, m.Length);
        richTextBox1.SelectionColor = Color.Cyan;
    }
}

答案 1 :(得分:0)

You can try with this:

private void btn_Search_Click(object sender, EventArgs e)
{
    var wordsToHighlight = new List<string>()
    {
        "Exit", "Close", "Leave"
    };

    if (!string.IsNullOrWhiteSpace(richTextBox1.Text))
    {
        foreach (var word in wordsToHighlight)
        {
            int index = 0;
            while (index != -1)
            {
                richTextBox1.SelectionColor = Color.Cyan;
                index = richTextBox1.Find(word, index + word.Length - 1, richTextBox1.TextLength, RichTextBoxFinds.None);
            }
        }
    }
}

Example (I changed SelectionColor to red because it's easier to notice it):

Example of highlighting