Answers to Split by commas but not within brackets using regexp ( 3 )

  1. 2017-01-07 03:01

    If expected result are two strings, irrespective of whether or not strings are parseable as javascript object or valid JSON you can use Array.prototype.reduce(), String.prototype.split(), String.prototype.replace()

    var str = "[1, '15', [false]], [[], 'sup']";
    
    var res = str.split(/,/).reduce((arr, text) => {
    
      text = text.trim();
    
      if (arr.length === 0) {
        arr.push([]);
      }
     
      if (/^\[/.test(text) && !/\]$/.test(text)) {
         arr[arr.length === 1 ? 0 : arr.length - 1].push(text.slice(1));
         return arr
      }
     
      if (!/^\[/.test(text) && /\]$/.test(text)) {
         arr[arr.length === 1 ? 0 : arr.length - 1].push(text.slice(0, -1));
         return arr
      }
    
      if (!/^\[/.test(text) && !/\]$/.test(text) 
          || /^\[/.test(text) && /\]{2}$/.test(text) 
          || !/\[|\]/.test(text)) {
          arr[arr.length === 1 ? 0 : arr.length - 1].push(text);
         return arr
      }
      
      if (/^\[{2}/.test(text) && /\]$/.test(text)) {
         arr[arr.length - 1].push(text);
         return arr
      }
    
      return arr
    
    }, []);
    
    var strs = `[${res.join()}]`.replace(/"/g, "").split(/,(?=\[{2})|"(?=")/);
    
    console.log(`str1:${strs[0]}\nstr2:${strs[1]}`);

  2. 2017-01-07 03:01

    If string is proper array-like string... maybe this is worth a try, too:

     var regex = /(\[.*?\]\])|(\[\[.*?\]$)|(\[(.*?)\])|(,)/gm;
    

    var regex = /(\[.*?\]\])|(\[\[.*?\]$)|(\[(.*?)\])|(,)/gm;
    str = "[1, '15', [false]], [[], 'sup']";
    /*str="[1, [30] [false][,]], [[]false, 'sup'[]]";
    str="[[] []], [1,4,5[8]]";
    str="[[1,2,3],[3,6,7]],[[],566,[]]";
    str="[[],[]],['duh,[],'buh',[]]";
    
    str="[1,2,3],[5,'ggg','h']"*/
    
    
    arr=[];
    while ((matches = regex.exec(str)) !== null) {
    if(matches[0]!==',')
    arr.push(matches[0]);
    
      
    }
    
    console.log(arr);

    So, basically, match alternative groups, loop through results, keep non-comma matches. This will fail, probably, in some cases...but, should be tested more.

  3. 2017-01-07 04:01

    Regexp is not well-suited to situations like this involving nesting. You might want to write a tiny parser:

    function parse(str) {
      let result = [], item = '', depth = 0;
    
      function push() { if (item) result.push(item); item = ''; }
    
      for (let i = 0, c; c = str[i], i < str.length; i++) {
        if (!depth && c === ',') push();
        else {
          item += c;
          if (c === '[') depth++;
          if (c === ']') depth--;
        }
      }
      
      push();
      return result;
    }
            
    console.log(parse("[1, '15', [false]], [[], 'sup']"));

    You may want to tweak this to handle spaces around the commas, unbalanced square brackets, etc.

Leave a reply to - Split by commas but not within brackets using regexp

◀ Go back