You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
A regexp for a number is: `pattern:-?\d+(\.\d+)?`. We created it in previous tasks.
2
+
3
+
An operator is `pattern:[-+*/]`. We put a dash `pattern:-` the first, because in the middle it would mean a character range, we don't need that.
4
+
5
+
Note that a slash should be escaped inside a JavaScript regexp `pattern:/.../`.
6
+
7
+
We need a number, an operator, and then another number. And optional spaces between them.
8
+
9
+
The full regular expression: `pattern:-?\d+(\.\d+)?\s*[-+*/]\s*-?\d+(\.\d+)?`.
10
+
11
+
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+)?)`.
12
+
13
+
In action:
14
+
15
+
```js run
16
+
let reg =/(-?\d+(\.\d+)?)\s*([-+*\/])\s*(-?\d+(\.\d+)?)/;
17
+
18
+
alert( "1.2 + 12".match(reg) );
19
+
```
20
+
21
+
The result includes:
22
+
23
+
-`result[0] == "1.2 + 12"` (full match)
24
+
-`result[1] == "1"` (first parentheses)
25
+
-`result[2] == "2"` (second parentheses -- the decimal part `(\.\d+)?`)
26
+
-`result[3] == "+"` (...)
27
+
-`result[4] == "12"` (...)
28
+
-`result[5] == undefined` (the last decimal part is absent, so it's undefined)
29
+
30
+
We need only numbers and the operator. We don't need decimal parts.
31
+
32
+
So let's remove extra groups from capturing by added `pattern:?:`, for instance: `pattern:(?:\.\d+)?`.
33
+
34
+
The final solution:
35
+
36
+
```js run
37
+
functionparse(expr) {
38
+
let reg =/(-?\d+(?:\.\d+)?)\s*([-+*\/])\s*(-?\d+(?:\.\d+)?)/;
0 commit comments