Per Ström Per Ström - 1 month ago 22
Javascript Question

Regexp, capture between parentheses, javascript

I have regexp that extracts values between parentheses.

It's working most of the time but not when it ends with a parentheses

var val = 'STR("ABC(t)")';
var regExp = /\(([^)]+)\)/;.
var matches = regExp.exec(val);

console.log(matches[1]); //"ABC(t"


What I want is
"ABC(t)".


Any ideas how I can modify my regexp to Achive this?

Update
The value is always inside the parentheses.

Some examples:

'ASD("123")'; => '123'
'ASD(123)'; => '123'
'ASD(aa(10)asda(459))'; => 'aa(10)asda(459)'


So first there is some text (always text). Then there is a (, and it always ends with a ). I want the value between.

Answer

You may use greedy dot matching inside Group 1 pattern: /\((.+)\)/. It will match the first (, then any 1+ chars other than linebreak symbols and then the last ) in the line.

var vals = ['STR("ABC(t)")', 'ASD("123")', 'ASD(123)', 'ASD(aa(10)asda(459))'];
var regExp = /\((.+)\)/;
for (var val of vals) {
  var matches = regExp.exec(val);
  console.log(val, "=>", matches[1]);
}