【问题标题】:c# .Regex.replace ignore case not workingc# .Regex.replace 忽略大小写不起作用
【发布时间】:2014-10-02 09:05:30
【问题描述】:

这方面有很多问题,但没有一个能解决我的问题。我有一个 SQL 服务器数据库作为数据源、一个输入文本框和一个搜索按钮。输入文本并按下搜索按钮后,将显示包含搜索文本的行的下拉列表。用户选择他们想要查看的行,该信息将显示在网格视图中。 (返回 1 行)

我希望突出显示搜索到的文本。这就是我所拥有的,它应该可以工作,但我不知道为什么它不能:

foreach (GridViewRow row in searchTextGridView2.Rows)
        {
            string text = searchText_txt.Text; //Text that was entered in the search text field
            int length = searchTextGridView2.Columns.Count; //Number of Columns on the grid
            for (int i = 0; i < length; i++) //loop through each column
            {
                string newText = row.Cells[i].Text.ToString(); //Get the text in the cell
                if (newText.Contains(text)) //If the cell text contains the search text then do this
                {
                    string highlight = "<span style='background-color:yellow'>" + text + "</span>";
                    string replacedText = Regex.Replace(newText, text, highlight, RegexOptions.IgnoreCase);
                    row.Cells[i].Text = replacedText;
                }
            }
        }

上面的代码是在下拉选中项发生变化的事件中。 如果我搜索“claims”,它会突出显示该单词的所有实例,但如果我搜索“Claims”,它只会突出显示带有大写“C”的单词。任何帮助表示赞赏

【问题讨论】:

  • 我想指出的是,即使在修复了区分大小写的 Contains 问题之后,如果您搜索,您的代码仍将 (1) 将 x 的实例替换为 X X,以及 (2) 如果您搜索 .,请将所有内容替换为 .
  • 是的,现在就遇到了。我在想我必须获取搜索项的长度,在单元格中找到索引,然后使用这些变量将在单元格中找到的文本复制到一个新变量中,以便维护案例
  • 对于 (1),如果将 "&lt;span style='background-color:yellow'&gt;" + text + "&lt;/span&gt;" 切换为 "&lt;span style='background-color:yellow'&gt;$0&lt;/span&gt;"$0 会告诉正则表达式在替换中使用它匹配的文本。对于 (2),您可以在输入上使用 `Regex.Escape1。

标签: c# asp.net regex replace ignore-case


【解决方案1】:

您的问题不是来自 Replace() 方法 - 它是 Contains() 方法。

每当您在字符串上调用Contains() 时,它将执行case-sensitive 比较,因此以下行将始终返回false

"Some Claims".Contains("claims");

为了克服这个问题,你应该使用String.IndexOf(String, Int32) 方法:

for (int i = 0; i < length; i++) 
{
    string newText = row.Cells[i].Text.ToString(); 
    if (newText.IndexOf(text, StringComparison.CurrentCultureIgnoreCase) >= 0
    {
        string highlight = "<span style='background-color:yellow'>$0</span>";
        string replacedText = Regex.Replace(newText, text, highlight, RegexOptions.IgnoreCase);
        row.Cells[i].Text = replacedText;
    }
}

【讨论】:

  • 这听起来应该可以,但它没有:(虽然.Contains确实为我指明了正确的方向。我改用int index = newText.IndexOf(text, StringComparison.CurrentCultureIgnoreCase);,效果很好.. ty
  • @KieranQuinn,我的错;我确实想指出那个特定的超载,但完全忘记了。我已经编辑了答案。
  • @Rawling,你确定吗? MSDN 没有提到这种重载,Visual Studio 智能感知也没有。
  • @RePierre 抱歉,我说的绝对是垃圾。
猜你喜欢
  • 2011-06-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多