Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive regex: Unrecognized grouping construct

Tags:

c#

.net

regex

I have written a regex to parse a BibTex entry, but I think I used something that is not allowed in .net as I am getting a Unrecognized grouping construct exception.

Can anyone spot my mistake?

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

Can be seen at https://regex101.com/r/uM0mV1/1

like image 387
cholewa1992 Avatar asked Aug 18 '15 09:08

cholewa1992


1 Answers

This is how I would capture all the details in the string you provided:

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

See demo

This regex works well because C# regex engine keeps all captured texts in a stack, and it can be accessed via Groups["name"].Captures property.

The C# code showing how to use it:

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++;
}

Output:

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
like image 142
Wiktor Stribiżew Avatar answered Sep 21 '22 15:09

Wiktor Stribiżew