Tobias Møller Tobias Møller - 25 days ago 5
C# Question

Search button, not case sensitive accepting special characters

I have a search button "find next" that searches in a

RichTextBox
, the only problem is, when I search for "[e]" then it will mark any "e" in the
RichTextBox
. And if I search for "[", then the program will crash. Here is my code:

private void downBtn_Click(object sender, EventArgs e)
{
string SearchWord = textBox1.Text;
if (SearchWord.Length > 0)
{
if (SearchWord != prevWord)
{
index = 0;
prevWord = SearchWord;
}

Regex reg = new Regex(SearchWord, RegexOptions.IgnoreCase);

foreach (Match find in reg.Matches(richTextBox1.Text))
{
if (find.Index >= index)
{
richTextBox1.Select(find.Index, find.Length);
richTextBox1.Focus();
index = find.Index + find.Length;
break;
}
}
}
}

g t g t
Answer Source

Try escaping your search term so that it does not include characters used by regular expressions.

Use the Regex.Escape method to do so.

So you could change your code to:

string escapedSearchTerm = Regex.Escape(SearchWord)
Regex reg = new Regex(escapedSearchTerm, RegexOptions.IgnoreCase);