Search code examples
c#searchrichtextboxcase-insensitive

Make search terms on richtextbox case insensitive c#


I have a richtextbox that I've added a search and highlight function to but it will only search for exactly what the user types. I know this is because of the MatchCase property but none of the other options seem to do the job. Here is my code:

private void btnSourceSearch_Click(object sender, EventArgs e)
{
     int start = 0;
     int end = richTextBox1.Text.LastIndexOf(textBox1.Text);

     richTextBox1.SelectAll();
     richTextBox1.SelectionBackColor = Color.White;

     while(start < end)
     {
          richTextBox1.Find(textBox1.Text, start, richTextBox1.TextLength, RichTextBoxFinds.MatchCase);

          richTextBox1.SelectionBackColor = Color.Yellow;

          start = richTextBox1.Text.IndexOf(textBox1.Text, start) + 1;
     }
}

Any help would be greatly appreciated. It's probably simple but I've been looking at code for a good few hours over the last week and it's beginning to look a lot like the Matrix!

Thanks


Solution

  • I don’t know if you are familiar with regular expressions, but they are useful in this situation. I am not that familiar with them but felt I would give this a shot using them. Without them, using your approach, you will have to check somehow all the case possibilities. That’s where regular expressions are your friend. Below is the code that creates a regular expression from the text in the text box. Then I use that expression to get the Matches in the text in the RichTexBox to highlight. Hope this helps.

    private void button1_Click(object sender, EventArgs e) {
      richTextBox1.SelectAll();
      richTextBox1.SelectionBackColor = Color.White;
      if (textBox1.Text.Length < 1)
        return;
      string pattern = @"\b" + textBox1.Text.Trim() + @"\b";
      Regex findString = new Regex(pattern, RegexOptions.IgnoreCase);
      foreach (Match m in findString.Matches(richTextBox1.Text)) {
        richTextBox1.Select(m.Index, m.Length);
        richTextBox1.SelectionBackColor = Color.Yellow;
      }
    }