Skip to content

Commit 1fb782c

Browse files
authored
Merge pull request #630 from duianto/patch-3
Fix and add details to result array explanation
2 parents ad27098 + 0e2c41c commit 1fb782c

File tree

1 file changed

+10
-8
lines changed
  • 5-regular-expressions/09-regexp-groups/5-parse-expression

1 file changed

+10
-8
lines changed

5-regular-expressions/09-regexp-groups/5-parse-expression/solution.md

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
A regexp for a number is: `pattern:-?\d+(\.\d+)?`. We created it in previous tasks.
22

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.
3+
An operator is `pattern:[-+*/]`. We put the dash `pattern:-` first, because in the middle it would mean a character range, we don't need that.
44

55
Note that a slash should be escaped inside a JavaScript regexp `pattern:/.../`.
66

@@ -21,15 +21,17 @@ alert( "1.2 + 12".match(reg) );
2121
The result includes:
2222

2323
- `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)
24+
- `result[1] == "1.2"` (first group `(-?\d+(\.\d+)?)` -- the first number, including the decimal part)
25+
- `result[2] == ".2"` (second group`(\.\d+)?` -- the first decimal part)
26+
- `result[3] == "+"` (third group `([-+*\/])` -- the operator)
27+
- `result[4] == "12"` (forth group `(-?\d+(\.\d+)?)` -- the second number)
28+
- `result[5] == undefined` (fifth group `(\.\d+)?` -- the last decimal part is absent, so it's undefined)
2929

30-
We need only numbers and the operator. We don't need decimal parts.
30+
We only want the numbers and the operator, without the full match or the decimal parts.
3131

32-
So let's remove extra groups from capturing by added `pattern:?:`, for instance: `pattern:(?:\.\d+)?`.
32+
The full match (the arrays first item) can be removed by shifting the array `pattern:result.shift()`.
33+
34+
The decimal groups can be removed by making them into non-capturing groups, by adding `pattern:?:` to the beginning: `pattern:(?:\.\d+)?`.
3335

3436
The final solution:
3537

0 commit comments

Comments
 (0)