diff --git a/9-regular-expressions/11-regexp-groups/04-parse-expression/solution.md b/9-regular-expressions/11-regexp-groups/04-parse-expression/solution.md index ac67519bb..b23813395 100644 --- a/9-regular-expressions/11-regexp-groups/04-parse-expression/solution.md +++ b/9-regular-expressions/11-regexp-groups/04-parse-expression/solution.md @@ -10,8 +10,8 @@ The full regular expression: `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. +2. `pattern:[-+*/]` - the operator, +3. `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+)?)`. @@ -54,3 +54,17 @@ function parse(expr) { alert( parse("-1.23 * 3.45") ); // -1.23, *, 3.45 ``` + +As an alternative to using the non-capturing `?:`, we could name the groups, like this: + +```js run +function parse(expr) { + let regexp = /(?-?\d+(?:\.\d+)?)\s*(?[-+*\/])\s*(?-?\d+(?:\.\d+)?)/; + + let result = expr.match(regexp); + + return [result.groups.a, result.groups.operator, result.groups.b]; +} + +alert( parse("-1.23 * 3.45") ); // -1.23, *, 3.45; +``` \ No newline at end of file