Skip to main content
 首页 » 编程设计

c#之使用特殊字符时出现解析错误

2024年02月13日14wayfarer

我想在结果集中突出显示我的搜索字符串。当我的搜索字符串是 (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(),它将转义输入字符串,以便正则表达式引擎将其视为文字文本。