3

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?

rabah Rachid
  • 89
  • 1
  • 8
  • 3
    These are the kinds of things you probably don't want to attempt with regex, but a parser and a state machine. – Kevin DiTraglia Oct 15 '13 at 19:33
  • [Here's](http://stackoverflow.com/questions/546433/regular-expression-to-match-outer-brackets) a similar question with the same type answer as @KevinDiTraglia gave – Jonesopolis Oct 15 '13 at 19:39
  • @KevinDiTraglia: .NET's regex engine *has* a state machine. – Tim Pietzcker Oct 15 '13 at 20:10
  • 1
    Your regex matches what you want `{{text{{anothertext}}text{{andanothertext}}text}}`, because of the greediness of `(.*)`, if you had `(.*?)` (lazy quantifier) instead, you would only match `{{text{{anothertext}}` – polkduran Oct 15 '13 at 22:11

1 Answers1

2

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);
Tim Pietzcker
  • 297,146
  • 54
  • 452
  • 522