Skip to content Skip to sidebar Skip to footer

How To Check If The Number Of Open Braces Is Equal To The Number Of Close Braces?

How to check if the number of open braces is equal to the number of close braces using regular expressions? Here is the code: var expression1 = 'count(machineId)+count(toolId)'; va

Solution 1:

var expression1 = "count(machineId)+count(toolId)";
var expression2 = "count(machineId)+count(toolId))";

if (matches(expression1)) {
    alert("Matched"); // Triggered!
}
else {
    alert("Not matched");
}

if (matches(expression2)) {
    alert("Matched");
}
else {
    alert("Not matched"); // Triggered!
}

functionmatches(str) {
    try {
        newFunction(str);
        returntrue;
    }
    catch (e) {
        return !(e instanceofSyntaxError);
    }
}

This works because new Function() will cause a syntax error if your code is wrong. Catching the error means you can handle it safely and do whatever you want. Another good thing is that it doesn't execute the code, it just parses it. Basically, you're leveraging your task to the browser's parser.

It doesn't use regex, but it does check if your code is valid. Thus, it tells you if the parentheses match.

Solution 2:

Task can be simply solved without regexp, just count braces.

var a = 'count(machineId)+count())toolId)'var braces = 0;
for (var i=0, len=a.length; i<len; ++i) {
   switch(a[i]) {
       case'(' : 
          ++braces;
          break;
       case')' : 
           --braces;
           break;
   }
   if (braces < 0) {    
      alert('error');
      break;
   }
}

if (braces)
    alert('error');

Solution 3:

If your goal is to check if an expression is valid (it also means its substring that contains only brackets forms a correct bracket sequence), then regexps won't help you.

Regular expressions can only handle so called "regular languages" (though JS regexps maybe somewhat more powerful than their theoretic counterparts, the price of such power is greater complexity) while language of correct bracket sequences isn't regular.

See those slides — they can give you a glimpse into why regular expressions cannot recognize correct bracket sequence.

Nevertheless, the problem isn't so hard. You should just maintain a stack and go over your string from the left to the right. Every time you meet an opening bracket, you push it to the stack. When you meet a closing bracket, you pop top element of the stack and check if its type matches your one (yes, this algorithm can handle brackets of multiple types). At the end you should just check if the stack is empty.

In case you don't need to handle different types of brackets (you have only '(' and ')', for example) you can just maintain a variable openBrackets (essentially it would represent stack's size) and don't let it become negative.

Solution 4:

if (expression1.match(/\(/g).length === expression2.match(/\)/g).length) {
    // is equal
}

In order to make it work with strings containing no braces, you may use the following workaround:

((expression1.match(/\(/g) || []).length

Solution 5:

If you only care about the count why don't you try something like this.

if(expression1.split('(').length == expression1.split(')').length) {
  alert('matched');
}

Post a Comment for "How To Check If The Number Of Open Braces Is Equal To The Number Of Close Braces?"