Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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+)?)`.

Expand Down Expand Up @@ -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 = /(?<a>-?\d+(?:\.\d+)?)\s*(?<operator>[-+*\/])\s*(?<b>-?\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;
```