Home > Software engineering >  Why doesn't out of range indexes throw an exception for Regex GroupCollection?
Why doesn't out of range indexes throw an exception for Regex GroupCollection?

Time:06-23

Ordinarily if you try to access an array member that doesn't exist you get an "IndexOutOfRangeException".

However, for some reason, I don't get that for a Regex GroupCollection.

For example:

    var match = Regex.Match("", "a");
    var test = match.Groups[6];

Does not throw an exception, despite match having only 1 group.

Why does this happen?

CodePudding user response:

This is by design.

See the GroupCollection documentation:

If groupnum is not the index of a member of the collection, or if groupnum is the index of a capturing group that has not been matched in the input string, the method returns a Group object whose Group.Success property is false and whose Group.Value property is String.Empty.

I bolded the beginning of the sentence since it describes your current scenario: a regex pattern finds no matches in an empty string, the match is empty, and there is no group with ID = 6.

  • Related