Regex to grab strings between square brackets

前端 未结 6 536
[愿得一人]
[愿得一人] 2020-12-03 11:11

I have the following string: pass[1][2011-08-21][total_passes]

How would I extract the items between the square brackets into an array? I tried

相关标签:
6条回答
  • 2020-12-03 11:38

    I'm not sure if you can get this directly into an array. But the following code should work to find all occurences and then process them:

    var string = "pass[1][2011-08-21][total_passes]";
    var regex = /\[([^\]]*)\]/g;
    
    while (match = regex.exec(string)) {
       alert(match[1]);
    }
    

    Please note: i really think you need the character class [^\]] here. Otherwise in my test the expression would match the hole string because ] is also matches by .*.

    0 讨论(0)
  • 2020-12-03 11:39

    add the global flag to your regex , and iterate the array returned .

     match(/\[(.*?)\]/g)
    
    0 讨论(0)
  • 2020-12-03 11:40
    'pass[1][2011-08-21][total_passes]'.match(/\[.+?\]/g); // ["[1]","[2011-08-21]","[total_passes]"]
    

    Explanation

    \[       # match the opening [
               Note: \ before [ tells that do NOT consider as a grouping symbol.
       .+?   # Accept one or more character but NOT greedy
    \]       # match the closing ] and again do NOT consider as a grouping symbol
    /g       # do NOT stop after the first match. Do it for the whole input string.
    

    You can play with other combinations of the regular expression https://regex101.com/r/IYDkNi/1

    0 讨论(0)
  • 2020-12-03 11:41

    You are almost there, you just need a global match (note the /g flag):

    match(/\[(.*?)\]/g);
    

    Example: http://jsfiddle.net/kobi/Rbdj4/

    If you want something that only captures the group (from MDN):

    var s = "pass[1][2011-08-21][total_passes]";
    var matches = [];
    
    var pattern = /\[(.*?)\]/g;
    var match;
    while ((match = pattern.exec(s)) != null)
    {
      matches.push(match[1]);
    }
    

    Example: http://jsfiddle.net/kobi/6a7XN/

    Another option (which I usually prefer), is abusing the replace callback:

    var matches = [];
    s.replace(/\[(.*?)\]/g, function(g0,g1){matches.push(g1);})
    

    Example: http://jsfiddle.net/kobi/6CEzP/

    0 讨论(0)
  • 2020-12-03 11:46

    [C#]

            string str1 = " pass[1][2011-08-21][total_passes]";
            string matching = @"\[(.*?)\]";
            Regex reg = new Regex(matching);
            MatchCollection matches = reg.Matches(str1);
    

    you can use foreach for matched strings.

    0 讨论(0)
  • 2020-12-03 11:48
    var s = 'pass[1][2011-08-21][total_passes]';
    
    r = s.match(/\[([^\]]*)\]/g);
    
    r ; //# =>  [ '[1]', '[2011-08-21]', '[total_passes]' ]
    
    example proving the edge case of unbalanced [];
    
    var s = 'pass[1]]][2011-08-21][total_passes]';
    
    r = s.match(/\[([^\]]*)\]/g);
    
    r; //# =>  [ '[1]', '[2011-08-21]', '[total_passes]' ]
    
    0 讨论(0)
提交回复
热议问题