moxy
moxy

Reputation: 93

Regex to match contents in last pair of brackets

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

Answers (2)

Wombat_RW
Wombat_RW

Reputation: 161

Or as a one liner...

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

Upvotes: 1

Kobi
Kobi

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

Related Questions