Last active
January 3, 2021 09:16
-
-
Save maartenba/057df56267bf04f1eaad7a3502651b65 to your computer and use it in GitHub Desktop.
C# Regular Expression Match deconstruction
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
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
This would work also:
... because
GroupCollection
doesn't throw when you reference a nonexistent Group - so no need forGetGroupByIndex
.