我想用逗号分隔一个字符串,但不是当它们在括号内时.
例如:
"[1, '15', [false]], [[], 'sup']"
Run Code Online (Sandbox Code Playgroud)
会分裂成
[
"[1, '15', [false]]",
"[[], 'sup']"
]
Run Code Online (Sandbox Code Playgroud)
我试过/\,(?=(.*\[.*\])*.*\]{1})/我的正则表达式,我的逻辑是匹配逗号,后面没有偶数个'[]',其中有任何字符在中间和外部后跟一个']'.
小智 5
Regexp 不太适合这种涉及嵌套的情况。你可能想写一个小解析器:
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']"));Run Code Online (Sandbox Code Playgroud)
您可能需要调整它以处理逗号周围的空格、不平衡的方括号等。
如果预期结果是两个字符串,无论字符串是否可解析为javascript对象或有效,JSON您都可以使用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]}`);Run Code Online (Sandbox Code Playgroud)