tags:

views:

99

answers:

3

Hi,

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

Thanks in advance.

+5  A: 

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.

Michael Bray
The alternative syntax is `(?'TagName'.*)`.
Pavel Minaev
Thanks a lot for the answer. I don't know why I thought it would be bad.
Payne
+1  A: 

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

jspcal
Thank you so much for your answer, and for the link.
Payne
+2  A: 

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.

Mark Byers