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
  • 36,946
  • 82
  • 271
  • 487

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
  • 356,069
  • 52
  • 309
  • 320