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)"; var expression2 = "count(machineId)+count(toolId))";
These are the 2 expressions, where in the expression1
, the number of open brackets is equal to number of close brackets and in expression2
, the number of open brackets is not equal to number of close brackets. I need a regular expression which counts the number of open brackets and close brackets and gives me the alert. I need to check for valid syntax too.
if(expression1.......){ // here goes the regular expression alert("Matched"); } else{ alert("Not matched"); }
Search if the top of the stack is the opening bracket of the same nature. If this holds then pop the stack and continue the iteration , in the end if the stack is empty, it means all brackets are well-formed and return Balanced , else return Not Balanced.
Use Stack , while iterating through each character of the input string , to Push any opening brackets to the stack and to Pop the closing bracket if it matches the closing bracket of the latest opening bracket in the stack . At the end of the iteration, if the stack is empty, then all the brackets were balanced.
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! } function matches(str) { try { new Function(str); return true; } catch (e) { return !(e instanceof SyntaxError); } }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With