2012-02-15 62 views
1

我需要突出显示文本块中的搜索项。正则表达式替换matchEvaluator使用字符串数组

我最初的想法是循环搜索条件。但有没有更简单的方法?

这里是我使用的是循环思维...

public string HighlightText(string inputText) 
{ 
    string[] sessionPhrases = (string[])Session["KeywordPhrase"]; 
    string description = inputText; 

    foreach (string field in sessionPhrases) 
    { 
     Regex expression = new Regex(field, RegexOptions.IgnoreCase); 
     description = expression.Replace(description, 
             new MatchEvaluator(ReplaceKeywords)); 
    } 
    return description; 
} 

public string ReplaceKeywords(Match m) 
{ 
    return "<span style='color:red;'>" + m.Value + "</span>"; 
} 
+0

你是什么意思?这段代码对我来说很容易。你的意思是更高效,更短,更有用......。 – jhsowter 2012-02-15 05:41:04

+0

是的,效率更高。是否有一个正则表达式替换函数可以处理数组替换? – user713813 2012-02-15 05:50:52

+0

在你的领域使用Regex.Escape是非常重要的。否则,你可能会得到“正则表达式注入”,但不会像sql注入那样糟糕,但并不好。 – jessehouwing 2012-02-15 08:44:12

回答

1

你可能喜欢的东西代替循环:

string[] phrases = ... 
var re = String.Join("|", phrases.Select(s => Regex.Escape(s)).ToArray()); 
text = Regex.Replace(re, text, new MatchEvaluator(SomeFunction), RegexOptions.IgnoreCase); 
+0

您可能需要在其周围添加'@“\ b(”+ re + @“)\ b”;',以便仅突出显示完全匹配。 – jessehouwing 2012-02-15 08:45:34

+0

另请注意,当你使用这个构造时,你不再需要一个MatchEvaluator。 – jessehouwing 2012-02-15 08:49:49

+0

这是如何更有效率? – jhsowter 2012-02-15 23:30:59

0

上Qtax的回答扩展:

phrases = ... 

// Use Regex.Escape to prevent ., (, * and other special characters to break the search 
string re = String.Join("|", phrases.Select(s => Regex.Escape(s)).ToArray()); 

// Use \b (expression) \b to ensure you're only matching whole words, not partial words 
re = @"\b(?:" +re + @")\b" 

// use a simple replacement pattern instead of a MatchEvaluator 
string replacement = "<span style='color:red;'>$0</span>"; 
text = Regex.Replace(re, text, replacement, RegexOptions.IgnoreCase); 

不是说如果你已经在HTML内部替换了数据,使用Regex代替任何东西可能不是一个好主意如果有人搜索术语脚本

<<span style='color:red;'>script</span>> 

:荷兰国际集团的内容,你可能最终得到。

为了防止这种情况发生,you could use the HTML Agility Pack in combination with Regex

You might also want to check out this post which deals with a very similar issue

+1

您似乎认为“关键字”始终以单词字符开头和结尾。在建议使用'\ b'之前,我会得到一个裁决。 – 2012-02-15 10:04:44