Friday, October 17, 2008

Highlighting keywords in text using Regex.Replace

Why

I needed to take some text and bold certain keywords before returning the data to the web browser to enhance my Search Engine Optimization

Example

The following example shows how I achieved this although it does contain dummy data. I created a new C# 2005 Console App and added the following to the Main method:

string keywords = "Cat, rabbit, dog,hound, fox";
string text = "The cat spoke to the dog and told him what the rabbit did to the fox while the hound was sleeping.";

Console.WriteLine(HighlightKeywords(keywords, text));
Console.ReadLine();


Then added the follwoing static methods:

private static string HighlightKeywords(string keywords, string text)
{
// Swap out the , for pipes and add the braces
Regex r = new Regex(@", ?");
keywords = "(" + r.Replace(keywords, @"|") + ")";

// Get ready to replace the keywords
r = new Regex(keywords, RegexOptions.Singleline | RegexOptions.IgnoreCase);

// Do the replace
return r.Replace(text, new MatchEvaluator(MatchEval));
}

private static string MatchEval(Match match)
{
if (match.Groups[1].Success)
{
return "" + match.ToString() + "";

}

return ""; //no match
}

No comments: