Skip to content

Commit 6186fba

Browse files
authored
Merge pull request #392 from odsantos/update-en-capturing-groups
Update "Capturing groups" files
2 parents 32b2c1f + 33cb85c commit 6186fba

File tree

1 file changed

+16
-2
lines changed
  • 9-regular-expressions/11-regexp-groups/04-parse-expression

1 file changed

+16
-2
lines changed

9-regular-expressions/11-regexp-groups/04-parse-expression/solution.md

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,8 @@ The full regular expression: `pattern:-?\d+(\.\d+)?\s*[-+*/]\s*-?\d+(\.\d+)?`.
1010

1111
It has 3 parts, with `pattern:\s*` between them:
1212
1. `pattern:-?\d+(\.\d+)?` - the first number,
13-
1. `pattern:[-+*/]` - the operator,
14-
1. `pattern:-?\d+(\.\d+)?` - the second number.
13+
2. `pattern:[-+*/]` - the operator,
14+
3. `pattern:-?\d+(\.\d+)?` - the second number.
1515

1616
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+)?)`.
1717

@@ -54,3 +54,17 @@ function parse(expr) {
5454

5555
alert( parse("-1.23 * 3.45") ); // -1.23, *, 3.45
5656
```
57+
58+
As an alternative to using the non-capturing `?:`, we could name the groups, like this:
59+
60+
```js run
61+
function parse(expr) {
62+
let regexp = /(?<a>-?\d+(?:\.\d+)?)\s*(?<operator>[-+*\/])\s*(?<b>-?\d+(?:\.\d+)?)/;
63+
64+
let result = expr.match(regexp);
65+
66+
return [result.groups.a, result.groups.operator, result.groups.b];
67+
}
68+
69+
alert( parse("-1.23 * 3.45") ); // -1.23, *, 3.45;
70+
```

0 commit comments

Comments
 (0)