无法排除 .NET 中的非捕获组

Unable to exclude non-capturing groups in .NET

var regex = new Regex(@"^(?: )?\((\w+)\)$");
var value = " (HTML)";

//I tried to play around with the following but it captures the whole string
var match = ResourceTypeRegex.Match(resourceType);

//The following lines all evaluate to the entire string
match.Groups.OfType<Group>().SingleOrDefault();
match.Captures.OfType<Capture>().SingleOrDefault();
match.Groups[0].Captures.OfType<Capture>().SingleOrDefault();

我只想捕获 HTML 或任何字符串。

下面的所有示例将 return HTML 紧接在 &nbsp;( 之后和字符串末尾的 ) 之前。

(?<=&nbsp;\)) 是一种回顾,确保我们在 HTML 之前有 &nbsp;((但不会将其添加到捕获的结果中)。 (?=\)$) 是一个积极的先行检查,如果我们在字符串的末尾有 ) ($)。同样,) 不会被消耗,也不是匹配项的一部分。

Regex ResourceTypeRegex = new Regex(@"^(?:&nbsp;\()?(\w+)(?=\)$)");
var value = "&nbsp;(HTML)";
var result56 = ResourceTypeRegex.Match(value).Groups[1].Value;

输出为 HTML,没有圆括号。 (?:&nbsp;\()? 使 &nbsp;) 可选。

如果你使用.SingleOrDefault(),它只会return第0个捕获组,即等于整个匹配.

你的正则表达式可能有点不对?下面将returnHTML。您的正则表达式缺少第二次捕获。

var ResourceTypeRegex = new Regex(@"^(?: )?\((\w+)\)$");
var value = "&nbsp;(HTML)";

var match = ResourceTypeRegex.Match(value);

Console.WriteLine("'" + match.Groups[1] + "'");

要获取捕获,请使用组数组从索引 1 开始。

我不确定你为什么要对此使用 LINQ,但既然你坚持,你可以创建这个扩展方法:

public static IEnumerable<string> CapturingGroups(this GroupCollection c) {     
    var query = c.OfType<Group>().Select(g => g.Value);

    //We only want index 1 and over since 0 is actually the entire string
    //if (c.Count > 1)
        query = query.Skip(1);

    return query;
}

而不是使用 match.Groups[1],您可以将其更改为 Console.WriteLine("'{0}'",match.Groups.CapturingGroups().FirstOrDefault());

运行 示例:https://dotnetfiddle.net/097fo9

var match = Regex.Match(inputString, @"^&nbsp;\((?<yourMatch>.*?)\)$");
var value = match.Groups["yourMatch"].Value;