4

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"

abatishchev
  • 98,240
  • 88
  • 296
  • 433
abecker
  • 885
  • 1
  • 10
  • 15

2 Answers2

10

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

(?x) {{ ( (?: [^{}]+ | (?<open>{{) | (?<-open>}}) )* (?(open)(?!)) ) }}
Qtax
  • 33,241
  • 9
  • 83
  • 121
  • This is exactly what I wanted, thanks ! (I will read the whole doc about balancing groups also ;) ) – abecker Jun 08 '13 at 20:52
  • @Qtax: Thank you very much.., i looking for solution for this question " {{}} --> parenthesis ( ) " (?x) \( ( (?: [^()]+ | (?\() | (?<-open>\)) )* (?(open)(?!)) ) \) – Thulasiram Oct 30 '13 at 21:47
2

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.

Jon Purdy
  • 53,300
  • 8
  • 96
  • 166
  • Which is exactly what balancing groups do for you. And if you want to make it more verbose you can always add comments in the expression. ;-) – Qtax Jun 08 '13 at 20:52