PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, August 4, 2022

[FIXED] Why doesn't out of range indexes throw an exception for Regex GroupCollection?

 August 04, 2022     c#, exception, match, regex     No comments   

Issue

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?


Solution

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.



Answered By - Wiktor Stribiżew
Answer Checked By - Pedro (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing