1

使用 JavaScript 正则表达式,如何匹配最后一组括号中的内容?

input = "the string (contains) things like (35) )( with (foobar) and )( stuff";

desired_output = "foobar"

我尝试过的一切都过度匹配或完全失败。任何帮助,将不胜感激。

谢谢。

4

2 回答 2

2

一种选择是匹配不包含其他括号的括号,例如:

var tokens = input.match(/\([^()]*\)/g);
var last = tokens.pop();
于 2012-05-17T06:12:55.750 回答
1

或者作为一个班轮...

var last = input.match(/\([^()]*\)/g).pop().replace(/(\(|\))/g,"").replace(/(^\s+|\s+$)/g,"");
于 2012-05-17T16:29:48.633 回答