gpt4 book ai didi

c# - 使用命名的捕获组会导致不同的匹配

转载 作者:太空宇宙 更新时间:2023-11-03 12:07:14 25 4
gpt4 key购买 nike

给定正则表达式:^(Start\.)?(.+?)(\.|\.\2)?(End)?$

测试输入:Start.Word.WordEnd

我得到 Word对于“2”组:

enter image description here

但是,如果我将正则表达式更改为还包括捕获组的名称,我会得到不同的结果:

正则表达式:^(Start\.)?(?<capturedGroup>.+?)(\.|\.\2)?(End)?$

捕获的组是 Word.Word

enter image description here

这是在 .NET 4.7.2 中的(我也在 https://dotnetfiddle.net/ 中进行了测试,结果相同)。链接:

第一个案例:https://dotnetfiddle.net/o33G6Y

第二种情况:https://dotnetfiddle.net/4zJuaQ

我在 https://regex101.com/ 中对此进行了测试(设置为 PHP)并且我得到了预期的结果(都是 Word ),所以我认为这是一个 .NET 问题?请帮忙。

最佳答案

参见 .NET Grouping Constructs regex docs :

Named matched subexpressions are numbered consecutively from left to right after matched subexpressions.

因此,您的模式组按以下顺序解析:

^(Start\.)?(?<capturedGroup>.+?)(\.|\.\2)?(End)?$
^---1---^ ^-------- 4 --------^^---2---^ ^-3-^

调试时,可以查看真实的组数字ID:

enter image description here

您只需要使用命名组反向引用,\k<capturedGroup> , 或使用 \4而不是 \2 (这不是那么直观,所以我宁愿您使用前一种解决方案)。

  • ^(Start\.)?(?<capturedGroup>.+?)(\.|\.\k<capturedGroup>)?(End)?$ - Demo 1
  • ^(Start\.)?(?<capturedGroup>.+?)(\.|\.\4)?(End)?$ - Demo 2

输出:

enter image description here

关于c# - 使用命名的捕获组会导致不同的匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54338112/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com