Skip to content

Regex Groups missing in static call

15 July 2011

It turns out that static and instance Regex .NET differ in Groups treatment. Instance object allows access to groups in few different ways – by name, by index, all names and all numbers

but static object – does not.

Because groups are kept in protected internal collection extension method also cannot catch them.

The only way to list groups is by index, nevertheless they are anonymous or named.

This snippet

String txt = @"Today is 14.7.2011 г. last month was 14.6.2011 г.";
String pattern = @"(?<month>\d{1,2})\.(?<day>\d{1,2})\.(?<year>\d{4}|\d{2})";
MatchCollection statMatchis = Regex.Matches(txt, pattern);
foreach (Match match in statMatchis)
  if (!match.Success) { continue; }
  Console.WriteLine("Index: {0}, Length: {1}, Value: {2}", match.Index, match.Length, match.Value);
  Console.WriteLine("\tgroups for\t{0}:", match.Value);
  for (int i = 0; i < matches.Count; i++)
    Console.WriteLine("\tgroup No: {0}, Index: {1}, Length: {2}, Value:  {3}", i, match.Groups[i].Index, match.Groups[i].Length, match.Groups[i].Value);

will show groups but only by index. No names.

Static regex:
Index: 9, Length: 9, Value: 14.7.2011
        groups for      14.7.2011:
        group No: 0, Index: 9, Length: 9, Value:  14.7.2011
        group No: 1, Index: 9, Length: 2, Value:  14
        group No: 2, Index: 12, Length: 1, Value:  7
        group No: 3, Index: 14, Length: 4, Value:  2011



From → C#

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: