String equals based on Regex C#
I need to compare strings based on what is matched by a regex. So I decided to create a regex to pick the parts of a string that I felt was necessary for consideration for equals. When using a regex and leaving parts of the string outside use “non capturing groups”. Like “(\d+)(?:st|nd|rd|th)?” with will match a number and optional some postfix like “nd” as in 2nd.
public static class StringEqualsRegex { /// <summary> /// Equals the strings by regex. /// </summary> /// <param name="s1">The first string.</param> /// <param name="s2">The second string.</param> /// <param name="regex">The regex.</param> /// <returns><c>true</c> if the captured strings of s1 and s2 match, <c>false</c> otherwise.</returns> public static bool EqualsByRegex(this string s1, string s2, Regex regex) { /*Extension Method*/ return EqualStringByRegex(s1, s2, regex); } /// <summary> /// Equals the strings by regex. /// </summary> /// <param name="s1">The first string.</param> /// <param name="s2">The second string.</param> /// <param name="regex">The regex.</param> /// <returns><c>true</c> if the captured strings of s1 and s2 match, <c>false</c> otherwise.</returns> public static bool EqualStringByRegex(string s1, string s2, Regex regex) { string capturedS1 = GetCapturedString(s1, regex); string capturedS2 = GetCapturedString(s2, regex); return (capturedS1 != null && capturedS2 != null) && capturedS1.Equals(capturedS2); } private static string GetCapturedString(string s, Regex regex) { dynamic match = regex.Match(s); if ((match.Success)) { var sb = new StringBuilder(); for (var i = 1; i <= match.Groups.Count; i++) { foreach (Capture capture in match.Groups[i].Captures) { sb.Append(capture.Value); } } return sb.ToString(); } return null; } }
.
[wpdm_file id=1]