通常,如果您尝试访问一个不存在的数组成员,您会得到一个“IndexOutOfRangeException”。
但是,出于某种原因,我没有得到 Regex GroupCollection。
例如:
var match = Regex.Match("", "a");
var test = match.Groups[6];
不抛出异常,尽管 match
只有 1 个组。
为什么会这样?
最佳答案
这是设计使然。
参见 GroupCollection
documentation :
If
groupnum
is not the index of a member of the collection, or ifgroupnum
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 isfalse
and whoseGroup.Value
property is String.Empty.
我将句子的开头加粗,因为它描述了您当前的情况:a
正则表达式模式在空字符串中找不到匹配项,匹配项为空,并且没有 ID = 6 的组。
关于c# - 为什么超出范围的索引不会为 Regex GroupCollection 抛出异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72721380/