Parse an expression
A regexp for a number is: -?\d+(\.\d+)?. We created it in the previous task.
An operator is [-+*/]. The hyphen - goes first in the square brackets, because in the middle it would mean a character range, while we just want a character -.
The slash / should be escaped inside a JavaScript regexp /.../, we’ll do that later.
We need a number, an operator, and then another number. And optional spaces between them.
The full regular expression: -?\d+(\.\d+)?\s*[-+*/]\s*-?\d+(\.\d+)?.
It has 3 parts, with \s* between them:
-?\d+(\.\d+)?– the first number,[-+*/]– the operator,-?\d+(\.\d+)?– the second number.
To make each of these parts a separate element of the result array, let’s enclose them in parentheses: (-?\d+(\.\d+)?)\s*([-+*/])\s*(-?\d+(\.\d+)?).
In action:
We only want the numbers and the operator, without the full match or the decimal parts, so let’s “clean” the result a bit.
The full match (the arrays first item) can be removed by shifting the array result.shift().
Groups that contain decimal parts (number 2 and 4) (.\d+) can be excluded by adding ?: to the beginning: (?:\.\d+)?.
As an alternative to using the non-capturing ?:, we could name the groups, like this: