How to define regular expression of mathematical expression.please define a common regular expression for
5+4
5-3
5*6
6/2
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
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.