正则表达式匹配最后一对括号中的内容

时间:2012-05-17 06:04:00

标签: javascript regex

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

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

desired_output = "foobar"

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

感谢。

2 个答案:

答案 0 :(得分:2)

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

var tokens = input.match(/\([^()]*\)/g);
var last = tokens.pop();

答案 1 :(得分:1)

或作为一个班轮...

var last = input.match(/\([^()]*\)/g).pop().replace(/(\(|\))/g,"").replace(/(^\s+|\s+$)/g,"");