搜索按钮,不区分大小写,接受特殊字符

Search button, not case sensitive accepting special characters

我有一个在 RichTextBox 中搜索的搜索按钮 "find next",唯一的问题是,当我搜索“[e]”时,它会标记任何 "e" RichTextBox。如果我搜索“[”,程序就会崩溃。这是我的代码:

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

尝试转义您的搜索词,使其不包含正则表达式使用的字符。

使用 Regex.Escape 方法。

因此您可以将代码更改为:

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