我有以下代码用于显示搜索结果。
@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>
razor 中是否有任何 reg exp 可以忽略大小写?
最佳答案
您需要添加的是RegexOptions.IgnoreCase
作为 Regex.Replace
的最后一个参数过载:
@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))
}
Regex.Replace
的默认设置是 RegexOptions.None
,其中包括以下规则(强调区分大小写):
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.
注意:所有正则表达式选项均由 System.Text.RegularExpressions
命名空间提供,而不是 Razor 引擎本身。
关于asp.net-mvc - razor MVC RSS 中的 RegExp 搜索结果区分大小写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47453009/