Using named match groups in expressions

The following code will return the value user

Console.WriteLine(Regex.Match(@"test\user"@".*\\(.*?)$").Groups[1]);

Sometimes it makes life easier to refer to the group by name rather than its position (or GroupNum). To do this we need to insert the name into the expression. For example:

Console.WriteLine(Regex.Match(@"test\user"@".*\\(?<username>.*?)$").Groups["username"]);

In the code above, I've called the match group username. The Regex parser recognises this name because it is declared within the group brackets () and is preceded by a ?. i.e. (?<username>.*?). The Groups() method is overloaded to accept both GroupNum and GroupName.

Author Paul Hayman

Paul is the COO of kwiboo ltd and has more than 20 years IT consultancy experience. He has consulted for a number of blue chip companies and has been exposed to the folowing sectors: Utilities, Telecommunications, Insurance, Media, Investment Banking, Leisure, Legal, CRM, Pharmaceuticals, Interactive Gaming, Mobile Communications, Online Services.

Paul is the COO and co-founder of kwiboo (http://www.kwiboo.com/) and is also the creator of GeekZilla.

Add Comment

Name
Comment
 

Your comment has been received and will be shown once it passes moderation.