【发布时间】:2013-07-25 16:42:44
【问题描述】:
我想在结果集中突出显示我的搜索字符串。当我的搜索字符串是 (Java,PHP) 时,我的代码可以正常工作。 但是,当我的搜索字符串是 (Java,C++) 时,当代码执行此行时,我会遇到解析错误——
RegExp = new Regex(Search_String.Replace(" ", "|").Trim(), RegexOptions.IgnoreCase);
我了解 Regex 将 + 和 – 视为特殊字符,因此当我的搜索字符串为 (C++) 时 – 我使用了单独的正则表达式,如下所述 –
if (Search_String.Contains("++"))
{
RegExp = new Regex(@"C\+{2}");
}
我现在面临将这两个正则表达式结合起来的问题,以便我的代码在搜索字符串为 (Java,C++) 时工作。 任何人都可以建议解决此解析错误吗?
代码片段-
if (Search_String.Contains(","))
{
Search_String = Search_String.Replace(",", " ");
}
// Regular expression SetUp and add the Or operator.
RegExp = new Regex(Search_String.Replace(" ", "|").Trim(), RegexOptions.IgnoreCase);
// Highlight keywords by calling the delegate each time the keyword is found.
return RegExp.Replace(textInfo.ToTitleCase(InputTxt), new MatchEvaluator(ReplaceKeyWords));
public string ReplaceKeyWords(Match m)
{
return "<span class=highlight>" + m.Value + "</span>";
}
【问题讨论】:
-
Regex.Escape 是您要找的。span>
-
当我的搜索字符串是 (Java.C++) 时,我需要进行哪些修改才能通过下面的代码行 -- // 正则表达式设置并添加 Or 运算符。 RegExp = new Regex(Search_String.Replace(" ", "|").Trim(), RegexOptions.IgnoreCase);