Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@maartenba
Last active January 3, 2021 09:16
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maartenba/057df56267bf04f1eaad7a3502651b65 to your computer and use it in GitHub Desktop.
Save maartenba/057df56267bf04f1eaad7a3502651b65 to your computer and use it in GitHub Desktop.
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
Copy link

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
Copy link
Author

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