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
  • 95,331
  • 80
  • 293
  • 426
abecker
  • 875
  • 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
  • 32,254
  • 9
  • 78
  • 117
  • 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)(?!)) ) \) – 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
  • 51,678
  • 7
  • 93
  • 161
  • 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