Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression Named Groups: Good or Bad?

Tags:

c#

.net

regex

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

Thanks in advance.

like image 606
Payne Avatar asked Jan 22 '10 22:01

Payne


3 Answers

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.

like image 179
Michael Bray Avatar answered Sep 27 '22 20:09

Michael Bray


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.

like image 22
Mark Byers Avatar answered Sep 27 '22 19:09

Mark Byers


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

like image 40
jspcal Avatar answered Sep 27 '22 19:09

jspcal