正则表达式中的外部参数充当捕获组。来自 split (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split) 的文档:
如果分隔符是一个包含捕获的正则表达式
括号,然后每次匹配分隔符,结果
(包括任何未定义的结果)的捕获括号是
拼接到输出数组中。
您没有确切地说出您想用您的正则表达式实现什么,也许您想要这样的东西:
var str = "ab((cd))ef";
var arr = str.split(/[\)\(]+/);
console.log(arr); // ["ab", "cd", "ef"]
编辑:
每个括号单独匹配正则表达式,因此数组看起来像这样(每个括号匹配一行:
['ab', '('] // matched (
['ab', '(', '', '('] // matched ( (between the last two matches is the empty string
['ab', '(', '', '(', 'cd', ')'] // matched )
['ab', '(', '', '(', 'cd', ')', '', ')'] // matched )
['ab', '(', '', '(', 'cd', ')', '', ')', 'ef'] // string end
EDIT2:
需要的输出是:["ab", "(", "(", "cd", ")", ")", "ef"]
我不确定您是否可以通过一次拆分来做到这一点。最快和最安全的方法是过滤掉空字符串。我怀疑是否存在对正则表达式进行单个拆分的解决方案。
var str = "ab((cd))ef";
var arr = str.split(/([\)\(])/).filter(function(item) { return item !== '';});
console.log(arr);