如何使用Regex获取2个括号之间的内容?

时间:2011-08-28 07:48:03

标签: 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的正则表达式是什么?

3 个答案:

答案 0 :(得分:2)

使用suat的正则表达式,并且由于您想要与组进行全局匹配,您需要使用循环来获取所有匹配项:

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"]

答案 1 :(得分:1)

此正则表达式/[^()]+/g匹配不是()的所有字符系列:

var s = '(Boxing Bag@bag.jpg@To punch and kick)'+ // I broke this for readability
        '(Wallet@wallet.jpg@To keep money in)'.match(/[^()]+/g)
console.log(s) // ["Boxing Bag@bag.jpg@To punch and kick",
               //  "Wallet@wallet.jpg@To keep money in"]

答案 2 :(得分:0)

我创建了一个名为 balanced 的小型javascript库来帮助完成这样的任务。正如@Paulpro所提到的,如果你在括号之间有内容,解决方案会中断,这就是平衡擅长的。

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"]

继承人JSFiddle示例