Reputation: 93
Using JavaScript regular expressions, how can I match the contents in the last set of brackets?
input = "the string (contains) things like (35) )( with (foobar) and )( stuff";
desired_output = "foobar"
Everything I have tried over-matches or fails entirely. Any help would be appreciated.
Thanks.
Upvotes: 1
Views: 2343
Reputation: 161
Or as a one liner...
var last = input.match(/\([^()]*\)/g).pop().replace(/(\(|\))/g,"").replace(/(^\s+|\s+$)/g,"");
Upvotes: 1
Reputation: 138037
One option is to match parentheses that do not contain other parentheses, for example:
var tokens = input.match(/\([^()]*\)/g);
var last = tokens.pop();
Upvotes: 2