为什么不超出范围索引对Regex组汇编的异常?

发布于 2025-02-09 16:35:12 字数 257 浏览 1 评论 0 原文

通常,如果您尝试访问不存在的数组成员,则会获得“ indexoutofrangeException”。

但是,由于某种原因,我没有为Regex集体汇编而理解。

例如:

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

尽管匹配只有1个组,但不要引发异常。

为什么会发生这种情况?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

浅唱ヾ落雨殇 2025-02-16 16:35:12

这是设计。

参见 groupCollection 文档

如果 groupNum 不是集合成员的索引,或者 groupnum 是尚未捕获组的索引该方法已在输入字符串中匹配,返回a group group.success 属性是 false and group.value 属性属性为 string.empty 。。

我对句子的开头进行了粗体,因为它描述了您当前的方案: a Regex模式在空字符串中没有匹配,该匹配是空的,并且没有ID = 6的组。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文