【问题标题】:Search button, not case sensitive accepting special characters搜索按钮,不区分大小写,接受特殊字符
【发布时间】:2018-03-02 09:18:17
【问题描述】:

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

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

【问题讨论】:

    标签: c# regex winforms search richtextbox


    【解决方案1】:

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

    使用Regex.Escape 方法这样做。

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-07
      • 1970-01-01
      • 1970-01-01
      • 2013-11-05
      • 2011-12-20
      • 2022-12-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多