Separate with commas but not in brackets using regexp

I want to split the string with commas, but not when they are inside the brackets.

For instance:

"[1, '15', [false]], [[], 'sup']" 

would be divided into

 [ "[1, '15', [false]]", "[[], 'sup']" ] 

I tried /\,(?=(.*\[.*\])*.*\]{1})/ for my regular expression, my logic is commas that are not followed by an even number '[]' with any symbols between them and after him, followed by one ']'.

+6
source share
3 answers

If the expected result consists of two lines, regardless of whether the lines can be processed as a 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
source

Regexp is not suitable for attachment situations. 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 can customize it to handle spaces between commas, unbalanced square brackets, etc.

+1
source

If the string is a valid array type string ... maybe this is also worth a try:

  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, compare alternative groups, view results, keep matches without a comma. In some cases, this will not work, but will most likely be checked more.

0
source

Source: https://habr.com/ru/post/1013849/


All Articles