samedi 27 juin 2015

RegEx to match nested parentheses including the start and end parentheses

string st = "this (a,b) and this (s,(r,t),u) is a test";
var regex = new Regex(@"\(([^()]+| (?<Level>\()| (?<-Level>\)))+(?(Level)(?!))\)", RegexOptions.IgnorePatternWhitespace);

foreach (Match c in regex.Matches(input))
{
  Console.WriteLine(c.Value.Trim('(', ')'));
}

The above C# code in .NET 4.5 correctly returns:

a,b
s,(r,t),u

But I need the output including the parentheses as:

(a,b)
(s,(r,t),u)

Aucun commentaire:

Enregistrer un commentaire