js 正则表达式如何匹配逗号分隔 不包含()之内的内容

dongqudamage
  • 2
新手上路,请多包涵

例如 var str="123(xxxx),456,dd(cc(xxxx),ff(xxxx))";
var newstr=str.split(/正则表达式/)
alert(nrewstr) //["123(xxxx)","456","dd(cc(xxxx),ff(xxxx))"]

回复
阅读 1.4k
1 个回答
✓ 已被采纳
function resolve($str)
{
    let str = $str.replace(/([^\(\),]*)([\(\),]?)/g, (function(){
        let deep = 0;
        let node = '';
        return function($all, $1, $2){
            switch($2)
            {
                case '(':
                    deep ++;
                    node += $all;
                    break;
                case ')':
                    deep --;
                    node += $all;
                    break;
                case ',':
                    if(deep <= 0)
                    {
                        node += $1;
                        let jsNode = JSON.stringify(node);
                        node = '';
                        return ','+jsNode;
                    }
                    else
                    {
                        node += $all;
                    }
                    break;
                default:
                    return ','+JSON.stringify(node);
            }
            return '';
        };
    })());

    return JSON.parse('['+str.substr(1)+']');
}

console.log(resolve('123(xxxx),456(,)ddd,dd(cc(xxxx),ff(xxxx))'));
宣传栏