正则表达式匹配精确的单词 – 搜索字符串突出显示

我正在使用以下两种方法来突出显示搜索关键字。 它工作正常,但也取得了部分词。

例如:

文字:“这是.net编程”搜索关键词:“是”

突出显示部分词和“是”

请让我知道正确的正则表达式以突出显示正确的匹配。

private string HighlightSearchKeyWords(string searchKeyWord, string text) { Regex exp = new Regex(@", ?"); searchKeyWord = "(\b" + exp.Replace(searchKeyWord, @"|") + "\b)"; exp = new Regex(searchKeyWord, RegexOptions.Singleline | RegexOptions.IgnoreCase); return exp.Replace(text, new MatchEvaluator(MatchEval)); } private string MatchEval(Match match) { if (match.Groups[1].Success) { return "" + match.ToString() + ""; } return ""; //no match } 

你真的只需要在你的“(\ b”和“\ b)”之前使用@,因为字符串“\ b”不会像你期望的那样是“\ b”。 但我也尝试用替换模式制作另一个版本而不是完整的方法。

这个怎么样:

 private string keywordPattern(string searchKeyword) { var keywords = searchKeyword.Split(',').Select(k => k.Trim()).Where(k => k != "").Select(k => Regex.Escape(k)); return @"\b(" + string.Join("|", keywords) + @")\b"; } private string HighlightSearchKeyWords(string searchKeyword, string text) { var pattern = keywordPattern(searchKeyword); Regex exp = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Singleline); return exp.Replace(text, @"$0"); } 

用法:

 var res = HighlightSearchKeyWords("is,this", "Is this programming? This is .net Programming."); 

结果:

 Is this programming? This is .net Programming. 

更新为使用\ b和简化的替换模式。 (旧的使用(^ | \ s)而不是第一个\ b和($ | \ s)而不是最后一个\ b。所以它也适用于不仅包括单词字符的搜索词。

更新为逗号表示法以获取搜索字词

更新忘了Regex.Escape – 现在添加。 否则搜索“\ w”会炸掉东西:)

更新了评论;)

试试这个固定的行:

 searchKeyWord = @"(\b" + exp.Replace(searchKeyWord, @"|") + @"\b)"; 

您需要将关键字括在一个不匹配的组中,否则您将获得误报 (如果您使用多个以逗号分隔的关键字,如示例中所示)!

 private string EscapeKeyWords(string searchKeyWord) { string[] keyWords = searchKeyWord.Split(','); for (int i = 0; i < keyWords.Length; i++) keyWords[i] = Regex.Escape(keyWords[i].Trim()); return String.Join("|", keyWords); } private string HighlightSearchKeyWords(string searchKeyWord, string text) { searchKeyWord = @"(\b(?:" + EscapeKeyWords(searchKeyWord) + @")\b)"; Regex exp = new Regex(searchKeyWord, RegexOptions.Singleline | RegexOptions.IgnoreCase); return exp.Replace(text, @"$0"); }