gpt4 book ai didi

c# - 如何使正则表达式只捕获内部组

转载 作者:太空宇宙 更新时间:2023-11-03 23:30:34 26 4
gpt4 key购买 nike

   var matches = Regex.Matches("abcde", "(?:ab(c))(d)").Cast<Match>().ToList();

在这种情况下 https://regex101.com/会告诉 'c' 和 'd' 匹配。但是 .Net 会说有一个组 'abcd' 有一个捕获 'abcd'。

如何设置 .net 的正则表达式以忽略非捕获组但返回内部组捕获。(让它成为一个允许嵌套的解决方案会很棒,因为我从对象的树结构递归地创建我的正则表达式)。

谢谢。

最佳答案

Match 对象包含组,您需要使用 Match.Groups 而不是捕获来获取捕获的文本。参见 MSDN Regex.Match reference :

Because a single match can involve multiple capturing groups, Match has a Groups property that returns the GroupCollection. The Match instance itself is equivalent to the first object in the collection, at Match.Groups[0] (Match.Groups(0) in Visual Basic), which represents the entire match.

你的

var matches = Regex.Matches("abcde", "(?:ab(c))(d)").Cast<Match>().ToList();

获取这个:

enter image description here

您可以按如下方式访问您的值:

var first_c= matches[0].Groups[1].Value;
var first_d= matches[0].Groups[2].Value;

使用命名捕获将使您能够以这种方式访问​​它们:

var matches = Regex.Matches("abcde", "(?:ab(?<myc>c))(?<myd>d)").Cast<Match>().ToList();
var first_c= matches[0].Groups["myc"].Value;
var first_d= matches[0].Groups["myd"].Value;

关于c# - 如何使正则表达式只捕获内部组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32389124/

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