Skip to main content
 首页 » 编程设计

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

2024年05月29日12webabcd

   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(); 

获取这个:

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

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;