More on Nested Constructs
I revisited the Jeff Friedl expression today ( Matching Nested Contructs ) and I'm really starting to scratch my head. Here's the pattern again:
text = @"before (nope (yes (here) okay) after"pattern =
@"\(
(?>
[^()]+
|
\( (?'DEPTH')
|
\) (?<-DEPTH>)
)*
(?(DEPTH)(?!))
\)";
In the previous post, I admitted to having no idea what this line meant:
(?(DEPTH)(?!))
It's a conditional evaluation statement (?(expr)yes[|no]) that is designed to fail the Match if the expr evaluates to true. The (?!) part forces failure (refer Mastering Regex 2nd Editing page 333). Here's a snippet which highlights this:
// Test one
string source = @"Darren" ;
string pattern = @"(?'MYTEST'Darren)" ;
Console.WriteLine( Regex.Match( source, pattern ).Groups["MYTEST"].Success ) ;
//Displays: True
// Test two - force failure
string source = @"Darren" ;
string pattern = @"(?'MYTEST'Darren)(?(MYTEST)(?!))" ;
Console.WriteLine( Regex.Match( source, pattern ).Groups["MYTEST"].Success ) ;
// Displays: False
My next goal is to understand why, given the following source and pattern, there is a Match but no text is consumed into Group 2:
source = "8 F 8 F ) 8 F ) ) " pattern = "((8*)?)*"