1

I used

let regExp = /\(([^)]+)\)/;

to extract

(test(())) 

from

aaaaa (test(())) bbbb

but I get only this

(test(()

How can I fix my regex ?

user310291
  • 35,095
  • 76
  • 252
  • 458

1 Answers1

4

Don't use a negative character set, since parentheses (both ( and )) may appear inside the match you want. Greedily repeat instead, so that you match as much as possible, until the engine backtracks and finds the first ) from the right:

console.log(
  'aaaaa (test(())) bbbb'
    .match(/\(.*\)/)[0]
);

Keep in mind that this (and JS regex solutions in general) cannot guarantee balanced parentheses, at least not without additional post-processing/validation.

CertainPerformance
  • 313,535
  • 40
  • 245
  • 254