简体   繁体   中英

Validate mathematical expressions using regular expression?

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

  1. It can be blank means nothing is entered

  2. If specified it will always start with an operator + or - or * or / and will always be followed by a number that can have any number of digits and the number can be decimal(contains . in between the numbers) or integer(no '.' symbol within the number). examples: *0.9 , +22.36 , - 90 , / 0.36365

  3. It can be then followed by what is mentioned in point 2 (above line). examples: *0.9+5 , +22.36*4/56.33 , -90+87.25/22 , /0.36365/4+2.33

Please help me out.

Something like this should work:

^([-+/*]\d+(\.\d+)?)*

Regexr Demo

  • ^ - beginning of the string
  • [-+/*] - one of these operators
  • \d+ - one or more numbers
  • (\.\d+)? - an optional dot followed by one or more numbers
  • ()* - the whole expression repeated zero or more times

You could try generating such a regex using moo and such:

(?:(?:((?:(?:[ \t]+))))|(?:((?:(?:\/\/.*?$))))|(?:((?:(?:(?<![\d.])[0-9]+(?![\d.])))))|(?:((?:(?:[0-9]+\.(?:[0-9]+\b)?|\.[0-9]+))))|(?:((?:(?:(?:\+)))))|(?:((?:(?:(?:\-)))))|(?:((?:(?:(?:\*)))))|(?:((?:(?:(?:\/)))))|(?:((?:(?:(?:%)))))|(?:((?:(?:(?:\()))))|(?:((?:(?:(?:\)))))))

This regex matches any amount of int, float, braces, whitespace, and the operators +-*/% .

However, expressions such as 2+ would still be validated by the regex, so you might want to use a parser instead.

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

This is java regex, but this is only if not have any braces

[+\-]?(([0-9]+\.[0-9]+)|([0-9]+\.?)|(\.?[0-9]+))([+\-/*](([0-9]+\.[0-9]+)|([0-9]+\.?)|(\.?[0-9]+)))*

Also this with braces in java code
In this case I raplace (..) to number (..), should matches without brace pattern

    //  without brace pattern
    static Pattern numberPattern = Pattern.compile("[+\\-]?(([0-9]+\\.[0-9]+)|([0-9]+\\.?)|(\\.?[0-9]+))([+\\-/*](([0-9]+\\.[0-9]+)|([0-9]+\\.?)|(\\.?[0-9]+)))*");
    static Pattern bracePattern = Pattern.compile("\\([^()]+\\)");

    public static boolean matchesForMath(String txt) {

        if (txt == null || txt.isEmpty()) return false;
        txt = txt.replaceAll("\\s+", "");
        if (!txt.contains("(") && !txt.contains(")")) return numberPattern.matcher(txt).matches();
        if (txt.contains("(") ^ txt.contains(")")) return false;
        if (txt.contains("()")) return false;

        Queue<String> toBeRematch = new ArrayDeque<>();
        toBeRematch.add(txt);
        while (toBeRematch.size() > 0) {
            String line = toBeRematch.poll();
            Matcher m = bracePattern.matcher(line);
            if (m.find()) {
                String newline = line.substring(0, m.start()) + "1" + line.substring(m.end());
                String withoutBraces = line.substring(m.start() + 1, m.end() - 1);
                toBeRematch.add(newline);
                if (!numberPattern.matcher(withoutBraces).matches()) return false;
            }

        }
        return true;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM