Created
March 28, 2019 11:03
-
-
Save forensicmike/c102d11b67980d98fddd34a7c765591e to your computer and use it in GitHub Desktop.
Regular Expression Extensions
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
| static public class RegexExtensions | |
| { | |
| static public dynamic AsDynamic(this Match match) | |
| { | |
| var ret = new ExpandoObject() as IDictionary<string, Object>; | |
| foreach (var group in match.Groups.OfType<Group>()) | |
| { | |
| ret.Add(group.Name, group.Value); | |
| } | |
| return ret; | |
| } | |
| static public bool MatchThen(this Regex rgx, string input, Action<Match,dynamic> onSuccess, Action onFail = null) | |
| { | |
| var match = rgx.Match(input); | |
| if (match.Success) | |
| { | |
| onSuccess(match, match.AsDynamic()); | |
| return true; | |
| } | |
| else | |
| { | |
| if (onFail != null) | |
| onFail(); | |
| return false; | |
| } | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sick and tired of evaluating Regex groups using the kludgy
match.Groups["groupName"].Valuesyntax?How about having to store your match and then check for success?
This extension method allows you to eliminate both issues with the MatchThen function.
Example usage: