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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With