简体   繁体   中英

Javascript Regex to split line by comma

I want a regex expression for javascript which should split the line by comma and should not split the expressions inside the brackets

Eg:

BuiltInFunctions.REPLACE_FIRST,Type.STRING, Type.STRING, 2, getArgTypeIns(Type.STRING, Type.STRING, Type.BOOLEAN) 

to

BuiltInFunctions.REPLACE_FIRST
Type.STRING
Type.STRING
2
getArgTypeIns(Type.STRING, Type.STRING, Type.BOOLEAN)

Consider simplifying your operation:

var input = "BuildInFunctions...........";
var parentheses = [];
var replaced = input.replace(/\(.*?\)/g,function(m) {
    parentheses.push(m);
    return "{{PARENS:"+(parentheses.length-1)+"}}";
});
var parts = replaced.split(",");
var result = parts.map(function(part) {
    return part.replace(/\{\{PARENS:(\d+)\}\}/g,function(_,i) {return parentheses[i];});
});

The general idea is to extract all parenthesised expressions, then process the split, then put the parenthesised stuff back in. Much easier than trying to do it in one step with a regex (which I'm not sure is possible, to be honest)

This regex will split by commas, except those followed by brackets:

/,(?![^(]*\))/m

DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM