Case sensitive in search result with RegExp in razor MVC RSS

Viewed 353

I have the following code for displaying result from search.

@foreach (var str in (item.ContentText.Split(new char[] { '?', '<', '!', '<', '^', '>', '*', '>'}).Where(a => a.Contains((string)ViewData["searchTerm"]))))
{
                        @Html.Raw(Regex.Replace(str, (string)ViewData["searchTerm"],
 "<span style='background-color:rgb(245, 234, 157); color:rgb(243, 122, 122)'>" + (string)ViewData["searchTerm"] + "</span>"))
}
                    </a>

Is there any reg exp in razor for ignore case sensitive?

2 Answers

What you need to add is RegexOptions.IgnoreCase as the last argument of Regex.Replace overload:

@foreach (var str in (item.ContentText.Split(new char[] { '?', '<', '!', '<', '^', '>', '*', '>'}).Where(a => a.Contains((string)ViewData["searchTerm"]))))
{
     @Html.Raw(Regex.Replace(str, (string)ViewData["searchTerm"],
               "<span style='background-color:rgb(245, 234, 157); color:rgb(243, 122, 122)'>" + (string)ViewData["searchTerm"] + "</span>",
               RegexOptions.IgnoreCase))
}

The default setting for Regex.Replace is RegexOptions.None, which includes following rules (with emphasis about case sensitivity):

  • The pattern is interpreted as a canonical rather than an ECMAScript regular expression.

  • The regular expression pattern is matched in the input string from left to right.

  • Comparisons are case-sensitive.

  • The ^ and $ language elements match the beginning and end of the input string.

  • The . language element matches every character except \n.

  • Any white space in a regular expression pattern is interpreted as a literal space character.

  • The conventions of the current culture are used when comparing the pattern to the input string.

  • Capturing groups in the regular expression pattern are implicit as well as explicit.

Note: All regex options provided by System.Text.RegularExpressions namespace instead of Razor engine itself.

Use @RegexOptions.IgnoreCase , i think it will work for you.

Related