0

I have textbox and user write a formula and I get the text from textbox to split the parentheses .By the way I'm not trying to calculate formula I try to just get strings .I'm trying to get strings from nested parentheses Here is my code:

var txt = "((a-b)/month)/(c+d)";
var reg = /^\((.+)\)$/;
var newTxt = txt.split('(');
for (var i = 1; i < newTxt.length; i++) {
    var value = newTxt[i].split(')')[0];

    if (value == "") {
        value = txt.match(reg)[1];
    }
    console.log(value);
}

And my output is

   (a-b)/month)/(c+d
    a-b
    c+d

But I'm trying to get string between parentheses like

(a-b)/month
a-b
c+d
ozil
  • 6,930
  • 9
  • 33
  • 56

2 Answers2

4

This is another way

    var a = [], r = [];
    var txt = "(((a-b)+(f-g))/month)/(c+d)";
    for(var i=0; i < txt.length; i++){
        if(txt.charAt(i) == '('){
            a.push(i);
        }
        if(txt.charAt(i) == ')'){
            r.push(txt.substring(a.pop()+1,i));
        }
    }    
    alert(r);
Sujith
  • 206
  • 1
  • 6
2

This will capture the text in the outer parentheses, including the parentheses themselves:

(\((?>[^()]+|(?1))*\))

Output:

((a-b)/month)
(c+d)

Explanation:

  • ( start first capturing group
  • \( opening parenthesis
  • (?> look behind to check that...
  • [^()]+ ... there are no parentheses ...
  • | ... or that...
  • (?1) ... there is a nested group that has already been captured by this expression (recursion)
  • \) closing parenthesis
  • ) end of capturing group

Ah. Sorry. Your question is about JavaScript and JavaScript doesn't support look-behind.

James Newton
  • 6,623
  • 8
  • 49
  • 113