Real Dreams
Real Dreams

Reputation: 18020

Getting wrapped strings using RegEx

Consider following sting:

'aaa (d) ddd (xc) '

How I get following result using just match function:

["d","xc"]

I tried 'aaa (d) ddd (xc) '.match(/\(.*?\)/g) but it returns:["(d)","(xc)"]

Upvotes: 0

Views: 82

Answers (3)

lia ant
lia ant

Reputation: 408

Tweaking a bit Korikulum's regex...

If instead of anything .* specified anything that is not opening bracket:

'aaa (d) ddd (xc) (more) text'.match(/[^\(]+(?=\))/g) // >> ["d", "xc", "more"]

Upvotes: 1

elclanrs
elclanrs

Reputation: 94121

You can do it with replace instead of match. I answered a similar question today:

var str = 'aaa (d) ddd (xc)', 
    results = [];
str.replace(/\(([^()]+)\)/g, function(a,b) { results.push(b) });

console.log(results); //=> ['d', 'xc']

Upvotes: 0

Korikulum
Korikulum

Reputation: 2599

Since JavaScript doesn't support look behind you could do this:

var a = 'aaa (d) ddd (xc)'.match(/\(.*?(?=\))/g);

for (var i = 0; i < a.length; i++)
  a[i] = a[i].slice(1);

Upvotes: 0

Related Questions