Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get text contained between brackets with regular expression?

Tags:

c#

regex

My second question of the day!

I want to get text contained between brackets (opening brackets and its closing brackets) using regex in c#. I use this regex :

@"\{\{(.*)\}\}

Here an example : if my text is :

text {{text{{anothertext}}text{{andanothertext}}text}} and text.

I want to get :

{{text{{anothertext}}text{{andanothertext}}text}}

but with this regex i get :

{{text{{anothertext}}

I know another solution to get my text but is there a solution with regex?

like image 427
rabah Rachid Avatar asked Jun 07 '26 21:06

rabah Rachid


1 Answers

Fortunately, .NET's regex engine supports recursion in the form of balancing group definitions:

Regex regexObj = new Regex(
    @"\{\{            # Match {{
    (?>               # Then either match (possessively):
     (?:              #  the following group which matches
      (?!\{\{|\}\})   #  (but only if we're not at the start of {{ or }})
      .               #  any character
     )+               #  once or more
    |                 # or
     \{\{ (?<Depth>)  #  {{ (and increase the braces counter)
    |                 # or
     \}\} (?<-Depth>) #  }} (and decrease the braces counter).
    )*                # Repeat as needed.
    (?(Depth)(?!))    # Assert that the braces counter is at zero.
    \}}               # Then match a closing parenthesis.", 
    RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline);
like image 196
Tim Pietzcker Avatar answered Jun 09 '26 11:06

Tim Pietzcker