Skip to content

Instantly share code, notes, and snippets.

@bunopus
Created November 3, 2014 21:08
Show Gist options
  • Save bunopus/db73387560e2aee15edc to your computer and use it in GitHub Desktop.
Save bunopus/db73387560e2aee15edc to your computer and use it in GitHub Desktop.
Highlight something in string using Regex (C#)
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);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment