Skip to content Skip to sidebar Skip to footer

Nested Parentheses Get String One By One

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 try

Solution 1:

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

Solution 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.

Post a Comment for "Nested Parentheses Get String One By One"