递归正则表达式:无法识别的分组构造

cho*_*992 6 .net c# regex

我写了一个正则表达式来解析一个BibTex条目,但我认为我使用了.net中不允许的东西,因为我得到了一个Unrecognized grouping construct 例外.

谁能发现我的错误?

(?<entry>@(\w+)\{(\w+),(?<kvp>\W*([a-zA-Z]+) = \{(.+)\},)(?&kvp)*(\W*([a-zA-Z]+) = \{(.+)\})\W*\},?\s*)(?&entry)*
Run Code Online (Sandbox Code Playgroud)

可以在https://regex101.com/r/uM0mV1/1上看到

Wik*_*żew 1

这就是我捕获您提供的字符串中的所有详细信息的方法:

@(?<type>\w+)\{(?<name>\w+),(?<kvps>\s*(?<attribute>\w+)\s*=\s*\{(?<value>.*?)},?\r?\n)+}
Run Code Online (Sandbox Code Playgroud)

查看演示

此正则表达式效果很好,因为 C# 正则表达式引擎将所有捕获的文本保留在堆栈中,并且可以通过Groups["name"].Captures属性访问它。

显示如何使用它的 C# 代码:

var pattern = @"@(?<type>\w+)\{(?<name>\w+),(?<kvps>\s*(?<attribute>\w+)\s*=\s*\{(?<value>.*?)},?\r?\n)+}";
var matches = Regex.Matches(line, pattern);
var cnt = 1;
foreach (Match m in matches)
{
    Console.WriteLine(string.Format("\nMatch {0}", cnt));
    Console.WriteLine(m.Groups["type"].Value);
    Console.WriteLine(m.Groups["name"].Value);
    for (int i = 0; i < m.Groups["attribute"].Captures.Count; i++)
    {
        Console.WriteLine(string.Format("{0} - {1}",
              m.Groups["attribute"].Captures[i].Value,
              m.Groups["value"].Captures[i].Value));
     }
     cnt++;
}
Run Code Online (Sandbox Code Playgroud)

输出:

Match 1
article
Gettys90
author - Jim Gettys and Phil Karlton and Scott McGregor
abstract - A technical overview of the X11 functionality. This is an update of the X10 TOG paper by Scheifler \& Gettys.
journal - Software Practice and Experience
volume - 20
number - S2
title - The {X} Window System, Version 11
year - 1990

Match 2
article
Gettys90
author - Jim Gettys and Phil Karlton and Scott McGregor
abstract - A technical overview of the X11 functionality. This is an update of the X10 TOG paper by Scheifler \& Gettys.
journal - Software Practice and Experience
volume - 20
number - S2
title - The {X} Window System, Version 11
year - 1990

Match 3
article
Gettys90
author - Jim Gettys and Phil Karlton and Scott McGregor
abstract - A technical overview of the X11 functionality. This is an update of the X10 TOG paper by Scheifler \& Gettys.
journal - Software Practice and Experience
volume - 20
number - S2
title - The {X} Window System, Version 11
year - 1990
Run Code Online (Sandbox Code Playgroud)