javascript, regex parse string content in curly brackets

MengQi Han picture MengQi Han · Mar 20, 2012 · Viewed 32.9k times · Source

i am new to regex. I am trying to parse all contents inside curly brackets in a string. I looked up this post as a reference and did exactly as one of the answers suggest, however the result is unexpected.

Here is what i did

var abc = "test/abcd{string1}test{string2}test" //any string
var regex = /{(.+?)}/
regex.exec(abc) // i got ["{string1}", "string1"]
             //where i am expecting ["string1", "string2"]

i think i am missing something, what am i doing wrong?

update

i was able to get it with /g for a global search

var regex = /{(.*?)}/g
abc.match(regex) //gives ["{string1}", "{string2}"]

how can i get the string w/o brackets?

Answer

Mike Samuel picture Mike Samuel · Mar 20, 2012
"test/abcd{string1}test{string2}test".match(/[^{}]+(?=\})/g)

produces

["string1", "string2"]

It assumes that every } has a corresponding { before it and {...} sections do not nest. It will also not capture the content of empty {} sections.