понедельник, 3 ноября 2014 г.

Highlight value in string using Regex (C#)

I wrote little class that highlight values in string wrapping them in <span> tag with specific class. Notice that regex will not touch text inside html tags. So text "<div someValue>someValue</div>" will become "<div someValue><span class=''highlight'>someValue</span></div>".

using System.Text.RegularExpressions;
public static class Highlighter
{
private const string MatchPattern = "(?<!<[^>]*)(?<matched>{0})";
private const string ReplacePattern = "<span class='highlight'>${matched}</span>";
public static string Highlight(string value, string pattern)
{
var patternEsc = string.Format(MatchPattern, Regex.Escape(pattern));
return Regex.Replace(value, patternEsc, ReplacePattern, RegexOptions.IgnoreCase);
}
}
view raw highlighter.cs hosted with ❤ by GitHub

1 комментарий: