为什么嵌套括号会在此正则表达式中导致空字符串?

wub*_*bbe 6 javascript regex parentheses

为什么嵌套括号会在此正则表达式中导致空字符串?

var str = "ab((cd))ef";
var arr = str.split(/([\)\(])/);
console.log(arr); // ["ab", "(", "", "(", "cd", ")", "", ")", "ef"] 
Run Code Online (Sandbox Code Playgroud)

我想要实现的是这个

["ab", "(", "(", "cd", ")", ")", "ef"] 
Run Code Online (Sandbox Code Playgroud)

Tib*_*bos 7

正则表达式中的外部参数充当捕获组.从split文档(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split):

如果separator是包含捕获括号的正则表达式,则每次匹配时,捕获括号的结果(包括任何未定义的结果)都会拼接到输出数组中.

你没有准确说出你想用你的正则表达式实现什么,也许你想要这样的东西:

var str = "ab((cd))ef";
var arr = str.split(/[\)\(]+/);
console.log(arr); // ["ab", "cd", "ef"] 
Run Code Online (Sandbox Code Playgroud)

编辑:

每个括号单独匹配正则表达式,因此数组看起来像这样(每个括号匹配一行:

['ab', '('] // matched (
['ab', '(', '', '('] // matched ( (between the last two matches is the empty string
['ab', '(', '', '(', 'cd', ')'] // matched )
['ab', '(', '', '(', 'cd', ')', '', ')'] // matched )
['ab', '(', '', '(', 'cd', ')', '', ')', 'ef'] // string end
Run Code Online (Sandbox Code Playgroud)

EDIT2:

所需的输出是: ["ab", "(", "(", "cd", ")", ")", "ef"]

我不确定你能用一次拆分做到这一点.最快,最安全的方法就是过滤掉空字符串.我怀疑是否存在针对正则表达式的单个拆分的解决方案.

var str = "ab((cd))ef";
var arr = str.split(/([\)\(])/).filter(function(item) { return item !== '';});
console.log(arr); 
Run Code Online (Sandbox Code Playgroud)