The regular expression you're after looks something like:
-?\d+(?:\.\d+)?([*/%+-]-?\d+(?:\.\d+)?)+
Basically this means:
NUMBER (OPER NUMBER)*
A number is defined as:
- Optional minus sign;
- One or more digits;
- Optionally a period followed by one or more digits.
Now the leading optional minus is not strictly in your requirements so you can safely drop it but without it you can't recognize:
-3*-4
which violates your condition of two operands together. To drop it just drop -?
from the expression (in both places) ie:
\d+(?:\.\d+)?([*/%+-]\d+(?:\.\d+)?)+
It's also not clear if you want to accept many operands or just one. If it's just one then:
-?\d+(?:\.\d+)?[*/%+-]-?\d+(?:\.\d+)?
or
\d+(?:\.\d+)?[*/%+-]\d+(?:\.\d+)?
or a variant allowing spaces (\s
). You will probably also want to capture the groups using parentheses.
You may want to alter that definition.
Also you could consider allowing spaces between numbers and operands.
An example of usage:
var s = "-11.32 * -34";
var r = /(-?\d+(?:\.\d+)?)\s*([*/%+-])\s*(-?\d+(?:\.\d+)?)/;
var m = r.exec(s);
if (m != null) {
alert("First: " + m[1] + "\nOperand: " + m[2] + "\nSecond: " + m[3]);
} else {
alert("Not found");
}