Payne
Payne

Reputation: 83

Regular Expression Named Groups: Good or Bad?

How do I create groups with names in C# using Regular expressions, and is it good practice?

Thanks in advance.

Upvotes: 8

Views: 1015

Answers (3)

Mark Byers
Mark Byers

Reputation: 839114

As others have pointed out the syntax is (?<GroupName>....).

Here's an example demonstrating how to create a group called Key and a group called Value, and equally important (but frequently forgotten) - how to extract the groups by name from the resulting match object:

string s = "foo=bar/baz=qux";
Regex regex = new Regex(@"(?<Key>\w+)=(?<Value>\w+)");
foreach (Match match in regex.Matches(s))
{
    Console.WriteLine("Key = {0}, Value = {1}",
        match.Groups["Key"].Value,
        match.Groups["Value"].Value);
}

I would normally not use named groups for very simple expressions, for example if there is only one group.

For more complex regular expressions with many groups containing complex expressions, it would probably be a good idea to use named groups. On the other hand, if your regular expression is so complicated that you need to do this, it might be a good idea to see if you can solve the problem in another way, or split it up your algorithm into smaller, simpler steps.

Upvotes: 2

jspcal
jspcal

Reputation: 51934

named capture groups are nice, usually tho with simpler regex's using the numerical capture group is probably more streamliney, some tips here:

http://www.regular-expressions.info/named.html

Upvotes: 1

Michael Bray
Michael Bray

Reputation: 15285

Give the group a tag name:

(?<TagName>.*)

I absolutely think this is good practice. Consider what happens when you change the regular expression. If you use indexes to pull data out, then the order of these groups could change. By naming them, you are specifying exactly the data that you think the group contains, so it's a form of self-documentation too.

Upvotes: 7

Related Questions