Skip to content

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!)

vartext="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!)

vartext="Use 3.14 for pi.";if(Regex.Match(text,@"(\d+)/(\d+)").TryGet(out(intN,intD)fraction))Console.WriteLine((double)fraction.N/fraction.D);elseConsole.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!)

vartext="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

Contributing

Stars

0 stars

Watchers

1 watching

Forks

Used by

Contributors

Languages