Javascript:用逗号分隔字符串,括号内除外

Vis*_*rma 2 javascript parsing

给定字符串形式:

'"abc",ab(),c(d(),e()),f(g(),zyx),h(123)'
Run Code Online (Sandbox Code Playgroud)

如何拆分它以获得以下数组格式:

abc
ab()
c(d(),e())
f(g(),zyx)
h(123)
Run Code Online (Sandbox Code Playgroud)

我尝试过普通的javascript拆分,但它不能按预期工作.尝试正则表达但尚未成功.

ken*_*bec 5

您可以跟踪括号,并在左右parens均衡时添加这些表达式.

例如-

function splitNoParen(s){
    var left= 0, right= 0, A= [], 
    M= s.match(/([^()]+)|([()])/g), L= M.length, next, str= '';
    for(var i= 0; i<L; i++){
        next= M[i];
        if(next=== '(')++left;
        else if(next=== ')')++right;
        if(left!== 0){
            str+= next;
            if(left=== right){
                A[A.length-1]+=str;
                left= right= 0;
                str= '';
            }
        }
        else A=A.concat(next.match(/([^,]+)/g));
    }
    return A;
}

var s1= '"abc",ab(),c(d(),e()),f(g(),zyx),h(123)';
splitNoParen(s1).join('\n');

/*  returned value: (String)
"abc"
ab()
c(d(),e())
f(g(),zyx)
h(123)
*/
Run Code Online (Sandbox Code Playgroud)


mel*_*cia 5

这可能不是最好或更精致的解决方案,也可能不适合每一种可能性,但根据您的示例,它可以工作:

var data = '"abc",ab(),c(d(),e()),f(g(),zyx),h(123)';
// Create a preResult splitting the commas.
var preResult = data.replace(/"/g, '').split(',');
// Create an empty result.
var result = [];

for (var i = 0; i < preResult.length; i++) {
    // Check on every preResult if the number of parentheses match.
    // Opening ones...
    var opening = preResult[i].match(/\(/g) || 0;
    // Closing ones...
    var closing = preResult[i].match(/\)/g) || 0;

    if (opening != 0 &&
        closing != 0 &&
        opening.length != closing.length) {
        // If the current item contains a different number of opening
        // and closing parentheses, merge it with the next adding a 
        // comma in between.
        result.push(preResult[i] + ',' + preResult[i + 1]);
        i++;
    } else {
        // Leave it as it is.
        result.push(preResult[i]);
    }
}
Run Code Online (Sandbox Code Playgroud)

演示