0

I have a text like

It's a beatiful {day|morning|{month|year}} and I {watch {a serie| a movie}|play games}

I want to get

day|morning|{month|year}

and

watch {a serie| a movie}|play games

from this text.

Currently I have a regex using /\{(.+?)\}/g but it's not working when there are brackets inside brackets. This is an example from what I currently have: https://www.regextester.com/?fam=105404

As you can see, {day|morning|{month|year}} is not selecting completely because there are nested braces. How can I fix this?

Barmar
  • 596,455
  • 48
  • 393
  • 495
JH.
  • 11
  • 2
  • 2
    Regular expressions are not a good tool for dealing with nested strings like this. You need to write a parser than counts left braces and doesn't complete the match until the count of right braces matches. – Barmar Oct 13 '18 at 15:12
  • Check out this question. Seems like `exec` is what you need: https://stackoverflow.com/questions/6323417/how-do-i-retrieve-all-matches-for-a-regular-expression-in-javascript – Eugene Tsakh Oct 13 '18 at 15:15
  • I fully agree with Barmar. In your particular example you can get the desired result by modifying the regex to `/\{(.+?)\}+/g`, and then cutting off the first and last character in each match. This will, however, *only* work in *special cases*, where the closing `}` are directly behind each other. – Carsten Massmann Oct 13 '18 at 15:16
  • Also duplicate ? https://stackoverflow.com/questions/4414339/recursive-matching-with-regular-expressions-in-javascript – apokryfos Oct 13 '18 at 15:16
  • @EugeneTsakh What does `exec` have to do with the nested braces? – Barmar Oct 13 '18 at 15:16
  • Okay, but It doesn't fix the nested braces if I use exec, right? – JH. Oct 13 '18 at 15:20
  • "/\{(.+?)\}+/g" is working and have the braces in front and after is not a problem! Thanks! – JH. Oct 13 '18 at 15:22

0 Answers0