Regex nested structure with special charaters

Viewed 55

I need to find a Regex in C# that is matching and returning strings from a nested structre delimited by $( and )$.

My input string is:

$(string1$(string2)$sometexthere$(string3$(string4)$texttext)$anothertext)$

The output must be :

$(string1$(string2)$sometexthere$(string3$(string4)$texttext)$anothertext)$
$(string2)$
$(string3$(string4)$texttext)$
$(string4)$

I have tried with this regex \$\([^\$]*\)\$ but it's only returning the most inner string2 and string4.

Is there a solution to return each match with regex ? or even through a loop ? ( $( and )$ can be replaced after by [ and ] )

1 Answers

You may use

(?=(?<result>\$\((?>[^()]+|(?<o>\()|(?<-o>\)))*(?(o)(?!))\)\$))

See the regex demo, grab each match.Groups["result"].Value.

enter image description here

C# code snippet:

var pattern = @"(?=(?<result>\$\((?>[^()]+|(?<o>\()|(?<-o>\)))*(?(o)(?!))\)\$))";
var results = Regex.Matches(text, pattern)
        .Cast<Match>()
        .Select(x => x.Groups["result"].Value)
        .ToList();

See the C# demo online.

Pattern details

  • (?= - a positive lookahead that will enable overlapping matches:
    • (?<result>\$\((?>[^()]+|(?<o>\()|(?<-o>\)))*(?(o)(?!))\)\$) - Group "result":
      • \$\( - $( substring
      • (?>[^()]+|(?<o>\()|(?<-o>\)))* - 1+ chars other than ( and ) or a ( pushed on to the "o" group stack or ) popped from the "o" group stack, 0 or more times
      • (?(o)(?!)) - a conditional that fails the match if Group "o" stack is not empty
      • \)\$ - a )$ substring
  • ) - end of the lookahead
Related