Tuesday, November 6, 2007

Highlighting matches using Regular Expressions in C#

Below is sample code on how to find matches to a particular regular expression in some body of text and surround each match with some html tags. For example, if the body of text is: string body = "This is just a test and is the body of text that we are trying to search"; After calling HighlightExpression(body); body will be This is just a <span class="highlight">test</span> and is the body of text that we are trying to search public string HighlightExpression(string body) { try { string expression = "test"; body = Regex.Replace(body, expression, new MatchEvaluator(HighlightUrls)); } catch (ArgumentException ex) { // Syntax error in the regular expression } } // this is a delegate that gets called for each match public string HighlightMatch(Match m) { return "<span class=\"highlight\">" + m.Value + "</span>"; }

No comments: