Reputation: 1640
We're a bit confused why this piece of code doesn't throw any error as we're expecting for an IndexOutOfRangeException
exception.
Regex re = new Regex(@"(\d+)");
Match result = re.Match("123456789");
Console.WriteLine(result.Groups[1000000000].Value);
Can anyone explain any thoughts about his?
Upvotes: 2
Views: 693
Reputation: 8938
I would just chalk this up to an implementation choice.
GroupCollection.Item Property (Int32) documentation does not indicate that it throws any exceptions: even -1
works:
Regex re = new Regex(@"(\d+)");
Match result = re.Match("123456789");
Console.WriteLine(result.Groups[1000000000].Value); // works: ""
Console.WriteLine(result.Groups[0].Value); // works: "123456789"
Console.WriteLine(result.Groups[-1].Value); // works: ""
Contrast this with DataColumnCollection.Item Property (Int32) documentation, which indicates it can throw IndexOutOfRangeException
:
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("A"));
DataColumn existent = dt.Columns[0]; // works
DataColumn nonexistent = dt.Columns[1]; // doesn't work - IndexOutOfRangeException
Maybe someone can provide insight into the reason(s) GroupCollection
handles nonsense without an exception and DataColumnCollection
handles the same nonsense with an exception, but I suspect it is little different than how each of us might elect to write a simple string-contains method (setting aside BCL support for this already):
bool StringContains(string inString, string lookForString)
{
if (inString.IsNullOrEmpty)
return false;
// blah
}
vs.
bool StringContains(string inString, string lookForString)
{
if (inString == null)
throw new ArgumentNullException("inString");
if (inString.Length == 0)
throw new ArgumentException("inString cannot be empty.");
// blah
}
Upvotes: 0
Reputation: 9668
Groups is not an array, it's indexed property. It's can return anything depends on it's code.
public Group this[int groupnum] { get; }
UPD From MSDN:
You can determine the number of items in the collection by retrieving the value of the Count property. Valid values for the groupnum parameter range from 0 to one less than the number of items in the collection.
The GroupCollection object returned by the Match.Groups property always has at least one member. If the regular expression engine cannot find any matches in a particular input string, the single Group object in the collection has its Group.Success property set to false and its Group.Value property set to String.Empty.
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.
Upvotes: 4