2017-09-21 9 views
0

J'ai un bouton de recherche "trouver ensuite" qui cherche dans un RichTextBox, le seul problème est, quand je cherche "[e]" alors il marquera tout "e" dans le RichTextBox. Et si je recherche "[", alors le programme va planter. Voici mon code:Bouton de recherche, non sensible à la casse acceptant des caractères spéciaux

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; 
      } 
     } 
    } 
} 

Répondre

2

Essayez échapper à votre terme de recherche afin qu'il ne comprend pas les caractères utilisés par des expressions régulières.

Utilisez la méthode Regex.Escape pour ce faire.

Ainsi, vous pouvez changer votre code:

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