Created
November 3, 2014 21:08
-
-
Save bunopus/db73387560e2aee15edc to your computer and use it in GitHub Desktop.
Highlight something in string using Regex (C#)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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