Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

javascript - How to split string while ignoring portion in parentheses?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...