2

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.

10
  • You escaped the wrong closing ), so your capturing group ends and then you match the ) (when it should be the other way around). Voting off-topic because the problem is a typographic error. Commented Oct 27, 2016 at 8:20
  • Unless there are specific restrictions on the input, this is pretty tough to solve with a regex. Depending on what is allowable in the input and what isn't, only an actual parser may be able to do this properly. Commented Oct 27, 2016 at 8:20
  • 1
    what should be matched in this case 'some text (num(10a ) ss) STR("ABC(t)")' ? Commented Oct 27, 2016 at 8:20
  • /("\w+\(.*?\)")/ should work in this case. Commented Oct 27, 2016 at 8:21
  • 2
    If the string is not part of a longer string, /\((.+)\)/ will do. More details about the input are necessary. Commented Oct 27, 2016 at 8:23

1 Answer 1

2

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]);
}

Answering the comment: If the texts to extract must be inside nested balanced parentheses, either a small parsing code, or XRegExp#matchRecursive can help. Since there are lots of parsing codes around on SO, I will provide XRegExp example:

var str = 'some text (num(10a ) ss) STR("ABC(t)")';
var res = XRegExp.matchRecursive(str, '\\(', '\\)', 'g');
console.log(res);
<script src="https://cdnjs.cloudflare.com/ajax/libs/xregexp/2.0.0/xregexp-all-min.js"></script>

Sign up to request clarification or add additional context in comments.

3 Comments

You should include some text (num(10a ) ss) STR("ABC(t)") in the test data set ;) :)
@GreenAsJade: No, OP has no such texts. Anyway, I can add a solution for this string, too. Need it?
I was just joking about the question in comments. The question in comments is designed to illustrate whether or not the regex is intended to parse matching parens, which I believe it is not.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.