Search code examples
c#asp.netregexreplaceignore-case

c# .Regex.replace ignore case not working


There are lots of questions around this but none solve my problem. I have a SQL server database as the datasource, an input text box and a search button. When the text is entered and the search button is pressed, a dropdown list of rows that contain the searched text is displayed. The user selects the row they want to look at and that information is displayed in a gridview. (1 row returned)

I want the searched text to be highlighted. This is what I have and it should work but I cant figure out why it doesn't:

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

The above code is inside the event for the dropdown selected item changed. If I searched for "claims", it will highlight all instances of that word but if I searched for "Claims", it only highlights words with the capital "C". Any help appreciated


Solution

  • Your problem is not from the Replace() method - it's the Contains() method.

    Whenever you call Contains() on a string it will perform case-sensitive comparison so the following line will always return false:

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

    In order to overcome this you should use String.IndexOf(String, Int32) method:

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