Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex embedded {{ matching

Tags:

c#

regex

I need to match the entire following statement:

{{CalendarCustom|year={{{year|{{#time:Y}}}}}|month=08|float=right}}

Basically whenever there is a { there needs to be a corresponding } with however many embedded { } are inside the original tag. So for example {{match}} or {{ma{{tch}}}} or {{m{{a{{t}}c}}h}}.

I have this right now:

(\{\{.+?(:?\}\}[^\{]+?\}\}))

This does not quite work.

like image 605
thirsty93 Avatar asked May 14 '11 14:05

thirsty93


1 Answers

The .NET regex engine allows recursive matching:

result = Regex.Match(subject,
    @"\{                   # opening {
        (?>                # now match...
           [^{}]+          # any characters except braces
        |                  # or
           \{  (?<DEPTH>)  # a {, increasing the depth counter
        |                  # or
           \}  (?<-DEPTH>) # a }, decreasing the depth counter
        )*                 # any number of times
        (?(DEPTH)(?!))     # until the depth counter is zero again
      \}                   # then match the closing }",
    RegexOptions.IgnorePatternWhitespace).Value;
like image 53
Tim Pietzcker Avatar answered Nov 15 '22 20:11

Tim Pietzcker