Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match text surrounded by "{{" and "}}"

Tags:

c#

regex

I'm looking for a Regex which can do this : My text :

"Blablabla {{ blabla1 }} blablablabla {{ blablabla2 {{ blabla3 }} }} blablabla"

What I want to extract :

"blabla1" and "blablabla2 {{ blabla3 }}"

Does anyone has an idea ?

I tried with : "{{(.)*}}" but it returns "blabla1" and "blabla3"

like image 259
abecker Avatar asked Dec 15 '22 10:12

abecker


2 Answers

You can use balancing groups for counting and matching nested constructs like these. For example:

(?x) {{ ( (?: [^{}]+ | (?<open>{{) | (?<-open>}}) )* (?(open)(?!)) ) }}
like image 129
Qtax Avatar answered Dec 21 '22 23:12

Qtax


This has nesting, so it’s not a regular grammar. Some regex engines have extensions to handle brace matching, but in general the best way to do this is by simply scanning the string and accumulating output in a List<string> while keeping track of the nesting depth.

like image 20
Jon Purdy Avatar answered Dec 22 '22 00:12

Jon Purdy