//Matching using Named Groups public string CreateHTMLMatches(Regex regex, RegexUseCase regexTest, List <string> GroupMatches) { string[] pen_colors = new string[] { "yellow", "green", "pink", "blue", "red", "grey" }; string HTMLMatch = ""; int[] char_captured = new int[regexTest.Value.Length]; //Each group will have an index, starting from 0 //Set array to -1, because index starts at 0 for (int i = 0; i < regexTest.Value.Length; ++i) { char_captured[i] = -1; } var matches = regex.Matches(regexTest.Value); foreach (Match m in matches) { if (m.Success) { for (int g = 0; g < GroupMatches.Count; ++g) { if (m.Groups[g].Success) { for (int i = 0; i < m.Groups[g].Length; ++i) { char_captured[m.Groups[g].Index + i] = g; } } } } } if (char_captured[0] >= 0) { HTMLMatch += "<span class='" + pen_colors[char_captured[0]] + "-highlight'>"; } HTMLMatch += WebUtility.HtmlEncode("" + regexTest.Value[0]); for (int i = 1; i < regexTest.Value.Length; ++i) { if (char_captured[i - 1] >= 0 && char_captured[i] != char_captured[i - 1]) { HTMLMatch += "</span>"; } if (char_captured[i - 1] != char_captured[i] && char_captured[i] >= 0) { HTMLMatch += "<span class='" + pen_colors[char_captured[i]] + "-highlight'>"; } HTMLMatch += WebUtility.HtmlEncode("" + regexTest.Value[i]); } if (char_captured[regexTest.Value.Length - 1] >= 0) { HTMLMatch += "</span>"; } //Dirty Dirty Fix for Groups. I don't know why :\ is being captured. Sorry bout that HTMLMatch = HTMLMatch.Replace(@"<span class='yellow-highlight'>" + WebUtility.HtmlEncode(@":\"), WebUtility.HtmlEncode(@":\") + @"<span class='yellow-highlight'>"); return(HTMLMatch); }
//Simple Matching public string CreateHTMLMatches(Regex regex, RegexUseCase regexTest, string MarkerColor) { string HTMLMatch = ""; bool[] char_captured = new bool[regexTest.Value.Length]; var matches = regex.Matches(regexTest.Value); foreach (Match m in matches) { if (m.Success) { for (int i = 0; i < m.Length; ++i) { char_captured[m.Index + i] = true; } } } if (char_captured[0]) { HTMLMatch += "<span class='" + MarkerColor + "-highlight'>"; } HTMLMatch += WebUtility.HtmlEncode("" + regexTest.Value[0]); for (int i = 1; i < regexTest.Value.Length; ++i) { if (char_captured[i - 1] && !char_captured[i]) { HTMLMatch += "</span>"; } if (!char_captured[i - 1] && char_captured[i]) { HTMLMatch += "<span class='" + MarkerColor + "-highlight'>"; } HTMLMatch += WebUtility.HtmlEncode("" + regexTest.Value[i]); } if (char_captured[regexTest.Value.Length - 1]) { HTMLMatch += "</span>"; } return(HTMLMatch); }