Validate mathematical expressions using regular expression?

前端 未结 3 1434
醉酒成梦
醉酒成梦 2020-11-29 08:50

I want to validate mathematical expressions using regular expression. The mathematical expression can be this

  1. It can be blank means nothing is entered

3条回答
  •  醉酒成梦
    2020-11-29 09:17

    If you want negative or positive expression you can write it like this>
    ^\-?[0-9](([-+/*][0-9]+)?([.,][0-9]+)?)*?$

    And a second one
    ^[(]?[-]?([0-9]+)[)]??([(]?([-+/*]([0-9]))?([.,][0-9]+)?[)]?)*$

    With parenthesis in expression but doesn't count the number you will need method that validate it or regex. // the method

     public static bool IsPairParenthesis(string matrixExpression)
        {
            int numberOfParenthesis = 0;
            foreach (char character in matrixExpression)
            {
                if (character == '(')
                {
                    numberOfParenthesis++;
                }
                if (character == ')')
                {
                    numberOfParenthesis--;
                }
            }
    
            if (numberOfParenthesis == 0)
            { return true; }
            return false;
        }
    

提交回复
热议问题