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 = /\(([^)]+)\)/;
Solution 1:
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);
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/xregexp/2.0.0/xregexp-all-min.js"></script>
Post a Comment for "Regexp, Capture Between Parentheses, Javascript"