我有一个字符串,我想通过使用逗号作为分隔符将其拆分为一个数组。我不希望括号之间的字符串部分被拆分,即使它们包含逗号也是如此。
例如:
"bibendum, morbi, non, quam (nec, dui, luctus), rutrum, nulla"
应该变成:
["bibendum", "morbi", "non", "quam (nec, dui, luctus)", "rutrum", "nulla"]
但是当我使用基本的 .split(",")
时,它返回:
["bibendum", " morbi", " non", " quam (nec", " dui", " luctus)", " rutrum", " nulla"]
我需要它返回:
["bibendum", " morbi", " non", " quam (nec, dui, luctus)", " rutrum", " nulla"]
感谢您的帮助。
最佳答案
var regex = /,(?![^(]*\)) /;
var str = "bibendum, morbi, non, quam (nec, dui, luctus), rutrum, nulla";
var splitString = str.split(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.
关于javascript - 如何在忽略括号中的部分的同时拆分字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39647555/