c# - 为什么超出范围的索引不会为 Regex GroupCollection 抛出异常?

标签 c# regex exception match

通常,如果您尝试访问一个不存在的数组成员,您会得到一个“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 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.

我将句子的开头加粗,因为它描述了您当前的情况:a 正则表达式模式在空字符串中找不到匹配项,匹配项为空,并且没有 ID = 6 的组。

关于c# - 为什么超出范围的索引不会为 Regex GroupCollection 抛出异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72721380/

相关文章:

php - 在php中使用正则表达式将字符串转换为包含数字和字母的数组?

c++ - 您如何跟踪每个功能提供的异常安全保证

c# - 从 String 解析枚举不起作用

c# - 从验证器类记录

javascript - 替换 JavaScript 中的捕获组内容

Javascript替换换行符

exception - ARM 处理器上的数据类型未对齐异常(0xA0000002)

java - 从jsp文件中调用java函数

c# - 更改 asp.net mvc 模型属性时无法访问数据库

c# - 是否存在 Dot.Net 4.5 异步计时器