WIP
This commit is contained in:
parent
fc0b18538d
commit
20547570ff
12 changed files with 376 additions and 186 deletions
|
@ -1,16 +1,19 @@
|
|||
A regexp for a number is: `pattern:-?\d+(\.\d+)?`. We created it in previous tasks.
|
||||
|
||||
An operator is `pattern:[-+*/]`.
|
||||
An operator is `pattern:[-+*/]`. The hyphen `pattern:-` goes first in the square brackets, because in the middle it would mean a character range, while we just want a character `-`.
|
||||
|
||||
Please note:
|
||||
- Here the dash `pattern:-` goes first in the brackets, because in the middle it would mean a character range, while we just want a character `-`.
|
||||
- A slash `/` should be escaped inside a JavaScript regexp `pattern:/.../`, we'll do that later.
|
||||
The slash `/` should be escaped inside a JavaScript regexp `pattern:/.../`, we'll do that later.
|
||||
|
||||
We need a number, an operator, and then another number. And optional spaces between them.
|
||||
|
||||
The full regular expression: `pattern:-?\d+(\.\d+)?\s*[-+*/]\s*-?\d+(\.\d+)?`.
|
||||
|
||||
To get a result as an array let's put parentheses around the data that we need: numbers and the operator: `pattern:(-?\d+(\.\d+)?)\s*([-+*/])\s*(-?\d+(\.\d+)?)`.
|
||||
It has 3 parts, with `pattern:\s*` between them:
|
||||
1. `pattern:-?\d+(\.\d+)?` - the first number,
|
||||
1. `pattern:[-+*/]` - the operator,
|
||||
1. `pattern:-?\d+(\.\d+)?` - the second number.
|
||||
|
||||
To make each of these parts a separate element of the result array, let's enclose them in parentheses: `pattern:(-?\d+(\.\d+)?)\s*([-+*/])\s*(-?\d+(\.\d+)?)`.
|
||||
|
||||
In action:
|
||||
|
||||
|
@ -29,11 +32,11 @@ The result includes:
|
|||
- `result[4] == "12"` (forth group `(-?\d+(\.\d+)?)` -- the second number)
|
||||
- `result[5] == undefined` (fifth group `(\.\d+)?` -- the last decimal part is absent, so it's undefined)
|
||||
|
||||
We only want the numbers and the operator, without the full match or the decimal parts.
|
||||
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 `pattern:result.shift()`.
|
||||
The full match (the arrays first item) can be removed by shifting the array `result.shift()`.
|
||||
|
||||
The decimal groups can be removed by making them into non-capturing groups, by adding `pattern:?:` to the beginning: `pattern:(?:\.\d+)?`.
|
||||
Groups that contain decimal parts (number 2 and 4) `pattern:(.\d+)` can be excluded by adding `pattern:?:` to the beginning: `pattern:(?:\.\d+)?`.
|
||||
|
||||
The final solution:
|
||||
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue