Skip to content

Instantly share code, notes, and snippets.

@maate
Created December 14, 2011 13:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maate/1476622 to your computer and use it in GitHub Desktop.
Save maate/1476622 to your computer and use it in GitHub Desktop.
Using .NET Regular Expressions to match and capture nested parenthesis
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace TestRegex
{
class Program
{
static void Main(string[] args)
{
var pattern2 = @"^(?>
\( (?<LEVEL>)(?<CURRENT>)
|
(?=\)) (?<LAST-CURRENT>) (?(?<=\(\k<LAST>) (?<-LEVEL> \)))
|
[^()]?
)*
(?(DEPTH)(?!))$";
var input = "2a+(3a-4)+(2b(3a-2))";
var match = Regex.Match(input, pattern2, RegexOptions.IgnorePatternWhitespace);
if (match.Success)
{
Console.WriteLine("Success");
foreach (var capture in match.Groups["LAST"].Captures)
{
Console.WriteLine(capture);
}
}
Console.ReadKey(false);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment