Skip to content

Instantly share code, notes, and snippets.

@maartenba maartenba/Program.cs
Last active Jun 6, 2017

Embed
What would you like to do?
C# Regular Expression Match deconstruction
class Program
{
static void Main(string[] args)
{
var regex = new Regex(@"(\w+) (\d+)");
var input = "John 9731879";
var (_, name, phone) = regex.Match(input);
Console.WriteLine(name);
Console.WriteLine(phone);
Console.ReadLine();
}
}
public static class RegexMatchExtensions
{
public static void Deconstruct(this Match match, out string group1)
{
group1 = GetGroupByIndex(match, 0);
}
public static void Deconstruct(this Match match, out string group1, out string group2)
{
group1 = GetGroupByIndex(match, 0);
group2 = GetGroupByIndex(match, 1);
}
public static void Deconstruct(this Match match, out string group1, out string group2, out string group3)
{
group1 = GetGroupByIndex(match, 0);
group2 = GetGroupByIndex(match, 1);
group3 = GetGroupByIndex(match, 2);
}
private static string GetGroupByIndex(Match match, int index)
{
if (match.Groups.Count > index)
{
return match.Groups[index].Value;
}
return null;
}
}
@duncansmart

This comment has been minimized.

Copy link

duncansmart commented Jun 6, 2017

This would work also:

public static void Deconstruct(this Match match, out string group1, out string group2, out string group3)
{
    group1 = match.Groups[0].Value;
    group2 = match.Groups[1].Value;
    group3 = match.Groups[2].Value;
    // etc ...
}

... because GroupCollection doesn't throw when you reference a nonexistent Group - so no need for GetGroupByIndex.

@maartenba

This comment has been minimized.

Copy link
Owner Author

maartenba commented Jun 6, 2017

Nice, thanks! I thought it would throw.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.