Skip to content

ejball/RegexMatchValues

Repository files navigation

RegexMatchValues

RegexMatchValues converts regular expression matches to strong types.

NuGet

Usage

The RegexMatchExtensions static class provides a few simple extension methods on Match that convert the capturing groups of the regular expression into a tuple. (Try it!)

var text = "Use 22/7 for pi.";
var (numerator, denominator) =
    Regex.Match(text, @"(\d+)/(\d+)").Get<(int, int)>();
Console.WriteLine((double) numerator / denominator);
// output: 3.142857142857143

Get<T>() throws InvalidOperationException if the match fails, so use one of the TryGet<T>() overloads if that is a possibility. (Try it!)

var text = "Use 3.14 for pi.";
if (Regex.Match(text, @"(\d+)/(\d+)").TryGet(out (int N, int D) fraction))
    Console.WriteLine((double) fraction.N / fraction.D);
else
    Console.WriteLine("No fraction found.");
// output: No fraction found.

To use named capturing groups, specify each group name in the order they should appear in the tuple. (Try it!)

var text = "Use 22/7 for pi.";
var (denominator, numerator) =
    Regex.Match(text, @"(?<nu>\d+)/(?<de>\d+)").Get<(int, int)>("de", "nu");
Console.WriteLine((double) numerator / denominator);
// output: 3.142857142857143

Other types besides tuples are also supported. See the remarks in the documentation for the full details.

About

Converts regular expression matches to strong types.

Topics

Resources

License

Contributing

Stars

Watchers

Forks

Contributors