如何检查开括号的数量是否等于闭括号的数量? [英] How to check if the number of open braces is equal to the number of close braces?

查看:103
本文介绍了如何检查开括号的数量是否等于闭括号的数量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检查开括号的数量是否等于使用正则表达式的闭括号数?

How to check if the number of open braces is equal to the number of close braces using regular expressions?

以下是代码:

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

这是2个表达式,其中 expression1 ,open括号的数量等于close括号的数量,而在 expression2 中,open括号的数量不等于close括号的数量。我需要一个正则表达式来计算开括号和小括号的数量,并给我提醒。我也需要检查有效的语法。

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


推荐答案

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.

这篇关于如何检查开括号的数量是否等于闭括号的数量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆