这是我如何捕获您提供字符串中的所有细节:
@(?<type>\w+)\{(?<name>\w+),(?<kvps>\s*(?<attribute>\w+)\s*=\s*\{(?<value>.*?)},?\r?\n)+}
请看:
查看 演示
这个正则表达式很有效,因为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++;
}
输出:
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
(?&...)
递归命名子模式。 - Wiktor Stribiżewstring.Format
构建正则表达式。 - Wiktor Stribiżew@(?<type>\w+)\{(?<name>\w+),(?<kvps>\s*(?<attribute>\w+)\s*=\s*\{(?<value>.*?)},?\r?\n)+}
。要访问所有键值对,我会使用.Groups["kvps"].Captures
属性和/或.Groups["attribute"].Captures
和.Groups["value"].Captures
。 - Wiktor Stribiżew