2011-08-28 224 views

回答

2

使用suat的正则表达式,因为你想做的事与集团全球配套,你需要使用一个循环让所有的比赛:

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

尽管如此,cwallenpoole演示的方法速度更快,因为它避免了回溯找到闭幕paren。 – Joey

1

此正则表达式/[^()]+/g匹配所有的字符序列不属于()

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

这也将匹配''中(富)等等(巴)'blah'。根据OP了解输入字符串的情况,这可能会也可能不会成为问题。 – Paulpro

0

我创建了一个名为balanced一些JavaScript库,帮助像这样的任务。正如@Paulpro所提到的,如果你在括号之间有内容,那么解决方案就会中断,这是平衡的优点。

var source = '(Boxing [email protected]@To punch and kick)Random Text([email protected]@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 [email protected]@To punch and kick", "[email protected]@To keep money in"] 

继承人JSFiddle示例

相关问题