How to split a line ignoring a part in parentheses?

I have a string that I want to split into an array using commas as separators. I do not want the parts of the string to be between the brackets that were separated, even if they contain commas.

For instance:

"bibendum, morbi, non, quam (nec, dui, luctus), rutrum, nulla" 

It should become:

 ["bibendum", "morbi", "non", "quam (nec, dui, luctus)", "rutrum", "nulla"] 

But when I use the basic .split(",") , it returns:

 ["bibendum", " morbi", " non", " quam (nec", " dui", " luctus)", " rutrum", " nulla"] 

I need to return it:

 ["bibendum", " morbi", " non", " quam (nec, dui, luctus)", " rutrum", " nulla"] 

Your help is appreciated.

+5
source share
4 answers

Instead of focusing on what you don't want, it is often easier to express as regular expression what you want, and match that with global regular expression:

 var str = "bibendum, morbi, non, quam (nec, dui, luctus), rutrum, nulla"; str.match(/[^,]+(?:\(+*?\))?/g) // the simple one str.match(/[^,\s]+(?:\s+\([^)]*\))?/g) // not matching whitespaces 
+2
source
 var regex = /,(?![^(]*\)) /; var str = "bibendum, morbi, non, quam (nec, dui, luctus), rutrum, nulla"; var splitString = str.split(regex); 

Here you go. Regular expression explanation:

 , //Match a comma (?! //Negative look-ahead. We want to match a comma NOT followed by... [^(]* //Any number of characters NOT '(', zero or more times /) //Followed by the ')' character ) //Close the lookahead. 
+5
source

You do not need regular regular expressions for this.

 s="bibendum, morbi, non, quam (nec, dui, luctus), rutrum, nulla" var current=''; var parenthesis=0; for(var i=0, l=s.length; i<l; i++){ if(s[i] == '('){ parenthesis++; current=current+'('; }else if(s[i]==')' && parenthesis > 0){ parenthesis--; current=current+')'; }else if(s[i] ===',' && parenthesis == 0){ console.log(current);current='' }else{ current=current+s[i]; } } if(current !== ''){ console.log(current); } 

Change console.log to concatenate the array or whatever you want.

+3
source
 var start = "bibendum, morbi, non, quam (nec, dui, luctus), rutrum, nulla"; start = start.replace(/ /g,''); console.log(start); var front = start.substring(0,start.lastIndexOf('(')).split(','); var middle = '('+start.substring(start.lastIndexOf('(')+1,start.lastIndexOf(')'))+')'; var end = start.substring(start.lastIndexOf(')')+2,start.length).split(','); console.log(front) console.log(middle) console.log(end) return front.concat(middle,end); 
0
source

All Articles