Javascript 如何使用正则表达式获取两个括号之间的内容?

Javascript 如何使用正则表达式获取两个括号之间的内容?,javascript,regex,Javascript,Regex,我有一个字符串如下所示: (Boxing Bag@bag.jpg@To punch and kick)(Wallet@wallet.jpg@To keep money in) 如何提取括号内的内容以获得2个字符串: Boxing Bag@bag.jpg@To punch and kick Wallet@wallet.jpg@To keep money in 使用JavaScript时的正则表达式是什么?此正则表达式匹配所有非(或)的字符序列: 使用的正则表达式,并且由于要对组进行全局匹配,因

我有一个字符串如下所示:

(Boxing Bag@bag.jpg@To punch and kick)(Wallet@wallet.jpg@To keep money in)
如何提取括号内的内容以获得2个字符串:

Boxing Bag@bag.jpg@To punch and kick
Wallet@wallet.jpg@To keep money in
使用JavaScript时的正则表达式是什么?

此正则表达式匹配所有非
的字符序列:

使用的正则表达式,并且由于要对组进行全局匹配,因此需要使用循环来获取所有匹配:

var str = '(Boxing Bag@bag.jpg@To punch and kick)(Wallet@wallet.jpg@To keep money in)';
var regex = new RegExp('\\((.*?)\\)', 'g');
var match, matches = [];
while(match = regex.exec(str))
    matches.push(match[1]);
alert(matches);
// ["Boxing Bag@bag.jpg@To punch and kick", "Wallet@wallet.jpg@To keep money in"]

我创建了一个名为的小javascript库来帮助完成类似的任务。正如@Paulpro所提到的,如果括号中有内容,那么解决方案就会中断,这正是balanced擅长的

var source = '(Boxing Bag@bag.jpg@To punch and kick)Random Text(Wallet@wallet.jpg@To keep money in)';

var matches = balanced.matches({source: source, open: '(', close: ')'}).map(function (match) {
    return source.substr(match.index + match.head.length, match.length - match.head.length - match.tail.length);
});

// ["Boxing Bag@bag.jpg@To punch and kick", "Wallet@wallet.jpg@To keep money in"]

下面是一个例子,cWallenPole演示的方法速度更快,因为它避免了回溯以查找结束参数。这也将匹配
(foo)blah(bar)
中的
blah
。这可能是问题,也可能不是问题,这取决于OP对输入字符串的了解程度。
var source = '(Boxing Bag@bag.jpg@To punch and kick)Random Text(Wallet@wallet.jpg@To keep money in)';

var matches = balanced.matches({source: source, open: '(', close: ')'}).map(function (match) {
    return source.substr(match.index + match.head.length, match.length - match.head.length - match.tail.length);
});

// ["Boxing Bag@bag.jpg@To punch and kick", "Wallet@wallet.jpg@To keep money in"]