Created
December 14, 2011 13:45
-
-
Save maate/1476622 to your computer and use it in GitHub Desktop.
Using .NET Regular Expressions to match and capture nested parenthesis
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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