javascript, regex parse string content in curly brackets

后端 未结 5 1222
忘掉有多难
忘掉有多难 2020-12-31 03:19

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, h

相关标签:
5条回答
  • 2020-12-31 03:31
    "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.

    0 讨论(0)
  • 2020-12-31 03:35
    var abc = "test/abcd{string1}test{string2}test" //any string
    var regex = /{(.+?)}/g
    var matches;
    
    while(matches = regex.exec(abc))
        console.log(matches);
    
    0 讨论(0)
  • 2020-12-31 03:38

    Nothing wrong. But you'll need to look at your capturing groups (the second element in the array) to get the content you wanted (you can ignore the first). To get all occurences, it's not enough to run exec once, you'll need to loop over the results using match.

    Edit: nevermind that, afaik you can't access capturing groups with match. A simpler solution would be using a positive lookahead, as Mike Samuel suggested.

    0 讨论(0)
  • 2020-12-31 03:44

    Try this:

    var abc = "test/abcd{string1}test{string2}test" //any string
    var regex = /{(.+?)}/g //g flag so the regex is global
    abc.match(regex) //find every match
    

    a good place to read about Regex in javascript is here, and a nice place to test is here

    good luck!

    0 讨论(0)
  • 2020-12-31 03:47

    This result:

    ["{string1}", "string1"]
    

    is showing you that for the first match, the entire regex matched "{string1}" and the first capturing parentheses matched "string1".

    If you want to get all matches and see all capturing parens of each match, you can use the "g" flag and loop through, calling exec() multiple times like this:

    var abc = "test/abcd{string1}test{string2}test"; //any string
    var regex = /{(.+?)}/g;
    var match, results = [];
    while (match = regex.exec(abc)) {
        results.push(match[1]);   // save first captured parens sub-match into results array
    }
    
    // results == ["string1", "string2"]
    

    You can see it work here: http://jsfiddle.net/jfriend00/sapfm/

    0 讨论(0)
提交回复
热议问题