Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript, regex parse string content in curly brackets

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?

like image 617
MengQi Han Avatar asked Mar 20 '12 18:03

MengQi Han


People also ask

How do you match curly brackets in regex?

To match literal curly braces, you have to escape them with \ . However, Apex Code uses \ as an escape, too, so you have to "escape the escape". You'll need to do this almost every time you want to use any sort of special characters in your regexp literally, which will happen more frequently than not.

Can you parse regex with regex?

No, it is not possible: regular expression language allows parenthesized expressions representing capturing and non-capturing groups, lookarounds, etc., where parentheses must be balanced.

How do you use parentheses in regex?

Use Parentheses for Grouping and Capturing. By placing part of a regular expression inside round brackets or parentheses, you can group that part of the regular expression together. This allows you to apply a quantifier to the entire group or to restrict alternation to part of the regex.

Can you parse a string in Javascript?

Javascript string to integer parsing with parseInt()Javascript parseInt parses strings into integers. If the passed string doesn't contain a number, it returns NaN as the result. You can parse a string containing non-numerical characters using parseInt as long as it starts with a numerical character.


2 Answers

"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.

like image 152
Mike Samuel Avatar answered Oct 28 '22 15:10

Mike Samuel


var abc = "test/abcd{string1}test{string2}test" //any string
var regex = /{(.+?)}/g
var matches;

while(matches = regex.exec(abc))
    console.log(matches);
like image 25
ZER0 Avatar answered Oct 28 '22 14:10

ZER0