Skip to content

Instantly share code, notes, and snippets.

@forensicmike
Created March 28, 2019 11:03
Show Gist options
  • Select an option

  • Save forensicmike/c102d11b67980d98fddd34a7c765591e to your computer and use it in GitHub Desktop.

Select an option

Save forensicmike/c102d11b67980d98fddd34a7c765591e to your computer and use it in GitHub Desktop.
Regular Expression Extensions
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;
}
}
}
@forensicmike
Copy link
Copy Markdown
Author

Sick and tired of evaluating Regex groups using the kludgy match.Groups["groupName"].Value syntax?
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:

var testString = "this is a pattern written by George";
var myRegex = new Regex(@"this is a pattern written by (?<personName>[\w\W]*?)$");
myRegex.MatchThen(testString, (match,result) => {
Console.WriteLine($"Turns out it was {result.personName}!");
}, () => {
// Note the fail method is optional and can be omitted
Console.WriteLine("No bueno!")
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment