c# balanced regex all text in brackets code example
Example: c# balanced regex all text in brackets
Regex re = new Regex(string.Format(@"^
{0} # Match first opeing delimiter
(?<inner>
(?>
{0} (?<LEVEL>) # On opening delimiter push level
|
{1} (?<-LEVEL>) # On closing delimiter pop level
|
(?! {0} | {1} ) . # Match any char unless the opening
)+ # or closing delimiters are in the lookahead string
(?(LEVEL)(?!)) # If level exists then fail
)
{1} # Match last closing delimiter
$", "<quote>", "</quote>"),
RegexOptions.IgnorePatternWhitespace | RegexOptions.IgnoreCase);
re.Match("<quote>inner text</quote>").Groups["inner"].Value == "inner text"
re.Match("<quote>a<quote>b</quote>c</quote>").Groups["inner"].Value == "a<quote>b</quote>c"