Regular expressions C# – is it possible to extract matches while matching?

You can use regex groups to accomplish that. For example, this regex:

(\d\d\d)-(\d\d\d\d\d\d\d)

Let’s match a telephone number with this regex:

var regex = new Regex(@"(\d\d\d)-(\d\d\d\d\d\d\d)");
var match = regex.Match("123-4567890");
if (match.Success)
    ....

If it matches, you will find the first three digits in:

match.Groups[1].Value

And the second 7 digits in:

match.Groups[2].Value

P.S. In C#, you can use a @”” style string to avoid escaping backslashes. For example, @”\hi\” equals “\\hi\\”. Useful for regular expressions and paths.

P.S.2. The first group is stored in Group[1], not Group[0] as you would expect. That’s because Group[0] contains the entire matched string.

Leave a Comment

tech