用空括号验证数学方程

时间:2022-02-22 21:24:13

I need to validate an equation, actually i have bracket validation but that don't validate if the brackets are empty only if brackets are balanced.

我需要验证一个等式,实际上我有括号验证,但是只有在括号平衡时才能验证括号是否为空。

For example 2 + 5 + (3 * {1 – 2}) = 4 return true, but 1 + () also return true and i need to return false.

例如2 + 5 +(3 * {1 - 2})= 4返回true,但1 +()也返回true,我需要返回false。

This is my code

这是我的代码

function mathFormulaValidator(string) {
    "use strict";

    let formulaSP = string.replace(/ /g, ""),
        arr = [],
        valid = true;

    for (let i = 0; i < formulaSP.length; i++) {
        let char = formulaSP.charAt(i);
        switch (char) {
            case '(':
                arr.push(1);
                break;
            case ')':
                if (arr.pop() != 1) {
                    valid = false;
                }
                break;
            case '[':
                arr.push(2);
                break;
            case ']':
                if (arr.pop() != 2) {
                    valid = false;
                }
                break;
            case '{':
                arr.push(3);
                break;
            case '}':
                if (arr.pop() != 3) {
                    valid = false;
                }
                break;
            default:
                console.error(char);
                break;
        }
    }
    return valid;
}

How can validate if the brackets are empty?? any ideas?

如何验证括号是否为空?有任何想法吗?

1 个解决方案

#1


1  

Use this:

string.match(/\(\)|{}|\[\]/) == null

This will return true if there are no empty (), {} or []

如果没有empty(),{}或[],则返回true

If there are any of those present, it will return false.

如果有任何存在,它将返回false。

For example:

"[]".match(/\(\)|{}|\[\]/) == null
false

"{(}".match(/\(\)|{}|\[\]/) == null
true

"2 + 5 + (3 * {1 – 2}) = 4".match(/\(\)|{}|\[\]/) == null
true

"1 + ()".match(/\(\)|{}|\[\]/) == null
false

Edit: Bergi is right, use it on formulaSP after stripping all spaces. Another limitation: it will return true for "(-)", "[+*/-]" or similar.

编辑:Bergi是对的,在剥离所有空格后在formulaSP上使用它。另一个限制:它将为“( - )”,“[+ * / - ]”或类似返回true。

#1


1  

Use this:

string.match(/\(\)|{}|\[\]/) == null

This will return true if there are no empty (), {} or []

如果没有empty(),{}或[],则返回true

If there are any of those present, it will return false.

如果有任何存在,它将返回false。

For example:

"[]".match(/\(\)|{}|\[\]/) == null
false

"{(}".match(/\(\)|{}|\[\]/) == null
true

"2 + 5 + (3 * {1 – 2}) = 4".match(/\(\)|{}|\[\]/) == null
true

"1 + ()".match(/\(\)|{}|\[\]/) == null
false

Edit: Bergi is right, use it on formulaSP after stripping all spaces. Another limitation: it will return true for "(-)", "[+*/-]" or similar.

编辑:Bergi是对的,在剥离所有空格后在formulaSP上使用它。另一个限制:它将为“( - )”,“[+ * / - ]”或类似返回true。