括号不捕获c#regex组

时间:2018-03-09 01:41:45

标签: c# .net regex

尝试使用以下代码从字符串中提取nameid

Regex.Matches
    "id: 123456, name: some dude",
    @"^id: (?<id>\d+), name: (?<name>[a-z]+(\s[a-z]+)?)"
);

但是,组和捕获的数量是1,并且没有命名捕获。我错过了什么?

编辑找到答案(谢谢大家!)但是为了将来的参考,事实证明这是因为我完全误解了API并且错误地访问了匹配项。我正在做这样的事情:

Console.WriteLine(matches.Count); // 1
foreach( Group g in matches ) {
    Console.WriteLine(g.Captures.Count); //1
    foreach( Capture c in g.Captures ) {
        Console.WriteLine(c.Value); // The whole string
    }
}

但现在我知道的更好了!

3 个答案:

答案 0 :(得分:2)

当您的正则表达式看起来没问题时,您查找匹配项的方式可能有问题:

Regex.Matches(
    "id: 123456, name: some dude",
    @"^id: (?<id>\d+), name: (?<name>[a-z]+(\s[a-z]+)?)"
)[0].Groups.Cast<Group>().Skip(2).Select(x => new {x.Name, x.Value})

产地:

    Name  Value
    id    123456 
    name  some dude 

如果您只需要特定的一个 - Regex.Matches(...)[0].Groups[2].Groups["id"]

请注意,您的代码使用Matches返回所有匹配项,如果您只是希望单项匹配 - 请使用Michael Randall answer

中显示的Match

答案 1 :(得分:1)

这很好用

String sample = "id: 123456, name: some dude";
Regex regex = new Regex(@"^id: (?<id>\d+), name: (?<name>[a-z]+(\s[a-z]+)?)");

Match match = regex.Match(sample);

if (match.Success)
{
   Console.WriteLine(match.Groups["id"].Value);
   Console.WriteLine(match.Groups["name"].Value);
}

当.Net小提琴再次运作时you can demo it here

<小时/> For Completness

Regex.Match Method (String)

  

在指定的输入字符串中搜索第一次出现的   正则表达式在Regex构造函数中指定。

Regex.Matches Method

  

在输入字符串中搜索所有正则表达式   并返回所有匹配。

Match.Groups Property

  

获取由正则表达式匹配的组的集合。组   然后可以从GroupCollection对象

中检索

GroupCollection.Item Property (String)

  

允许通过字符串索引访问集合的成员。   GroupName可以是已定义的捕获组的名称   通过正则表达式中的(?<name>)元素或字符串   表示由a定义的捕获组的编号   分组构造

答案 2 :(得分:1)

您应该使用Match代替Matches,并在正则表达式中使用非捕获组(?:)

Regex demo

String input = "id: 123456, name: some dude";

var output = Regex.Match(input, @"^id: (?<id>\d+), name: (?<name>.+)");

System.Console.WriteLine(output.Groups["id"]);
System.Console.WriteLine(output.Groups["name"]);

输出:

123456 
some dude