Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split string while ignoring portion in parentheses?

Tags:

javascript

I have a string that I want to split into an array by using the commas as delimiters. I do not want the portions of the string that is between parentheses to be split though even if they contain commas.

For example:

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

Should become:

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

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

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

I need it to return:

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

Your help is appreciated.

like image 990
Sultan Shakir Avatar asked Sep 22 '16 19:09

Sultan Shakir


2 Answers

var regex = /,(?![^(]*\)) /;
var str = "bibendum, morbi, non, quam (nec, dui, luctus), rutrum, nulla"; 

var splitString = str.split(regex);

Here you go. An explanation of the regex:

,     //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.
like image 94
Orpheus Avatar answered Nov 04 '22 14:11

Orpheus


You don't need fancy 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 for an array concatenation or what ever you want.

like image 30
OPSXCQ Avatar answered Nov 04 '22 13:11

OPSXCQ