简体   繁体   中英

problem in defining regular expression

How to define regular expression of mathematical expression.please define a common regular expression for

5+4
5-3
5*6
6/2

Ok, here's one which might be a bit more complicated than you need (hey, it's a regex!)

/^\s*-?\d+(?:\.\d+)?(?:\s*[+*\/\-]\s*-?\d+(?:\.\d+)?)+(?:\s*=\s*-?\d+(?:\.\d+)?)?$/

It allows for one or more operations, decimal numbers, and optionally an "equals" part at the end.

5 + 7
3 * 2 - 8
80.31 + 12 / 6
5 * 7 - 2 = 33
^\d+[+*\-/]\d+$

The specification is vague, but here's a readable regex using meta-regexing approach in Java.

    String regex =
        "num(?:opnum)*"
            .replace("op", "\\s*[*/+-]\\s*")
            .replace("num", "\\s*[+-]?\\d+(?:\\.\\d+)?\\s*");
    String[] tests = {
        "5+4",          // true
        "5 - 3",        // true
        "5 * 6 - 4",    // true
        "3.14159 = 0",  // true
        "A = B",        // false
        "5+ -4",        // true
        "5 * +4",       // true
        "5++5",         // true
        "5+++5",        // false
        "5+5+"          // false
    };
    for (String test : tests) {
        System.out.println(test + " " + test.matches(regex));
    }

Numbers may include optional decimal part, and a +/- sign. There could be multiple equalities.

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