1

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.

moxy
  • 93
  • 1
  • 7
  • 1
    I'm not entirely certain, but I have a feeling this fits the definition of something which is impossible to parse with a regular expression. – Stoive May 17 '12 at 06:09
  • 2
    Your original question was OK, but I'm pretty sure your current example is impossible by regex. Can you define what you mean by "last"? (note that the `( with .. and )` *ends* the last, whilst `(foobar)`'s opening bracket is the last opening bracket with a matching closing bracket. And must the set of brackets have no brackets within? For example, one could make a case for `(foobar) and)` being the "last" set of brackets (the last-occurring opening bracket with a close remaining in the string, and the last closing bracket in the string) – mathematical.coffee May 17 '12 at 06:12
  • Do you want just to get the contents or to have exact match? – Eugene Ryabtsev May 17 '12 at 06:13
  • have a look at first level example in http://stackoverflow.com/q/10447423/1176601 – Aprillion May 17 '12 at 06:14
  • I'm after the contents of the last set that contains no parenthesis. eg: "foobar" – moxy May 17 '12 at 06:27
  • Regular expressions are not good at matching, otherwise people would happily use them to parse HTML. – Salman A May 17 '12 at 07:20

2 Answers2

2

One option is to match parentheses that do not contain other parentheses, for example:

var tokens = input.match(/\([^()]*\)/g);
var last = tokens.pop();
Kobi
  • 135,331
  • 41
  • 252
  • 292
  • Thanks Kobi. That matches all the ones that don't contain parenthesis. eg: (contains), (35) and (foobar). Is there anyway to only match the contents of the last set without the pop? eg: foobar – moxy May 17 '12 at 06:32
  • Also, it seems pop returns the first match (eg: contains), not the last (eg: foobar) – moxy May 17 '12 at 06:48
  • 1
    @mgm: [here a jsfiddle](http://jsfiddle.net/F2kUk/) for this answer which cuts the brackets. – scessor May 17 '12 at 06:54
  • Thanks scessor! That works great. I just added a little error checking so that it doesn't pop null and it seems rock solid. Thanks again. – moxy May 17 '12 at 08:20
1

Or as a one liner...

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