Skip to content

Capturing groups #358

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Feb 14, 2022
Merged
Show file tree
Hide file tree
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
16 changes: 8 additions & 8 deletions 9-regular-expressions/11-regexp-groups/01-test-mac/solution.md
Original file line number Diff line number Diff line change
@@ -1,21 +1,21 @@
A two-digit hex number is `pattern:[0-9a-f]{2}` (assuming the flag `pattern:i` is set).
Un nombre hexadécimal à deux chiffres correspond à `pattern:[0-9a-f]{2}` (avec le marqueur `pattern:i`).

We need that number `NN`, and then `:NN` repeated 5 times (more numbers);
Nous avons besoin de ce nombre `NN`, et ensuite `:NN` répété 5 fois (pour les autres nombres) ;

The regexp is: `pattern:[0-9a-f]{2}(:[0-9a-f]{2}){5}`
L'expression régulière est : `pattern:[0-9a-f]{2}(:[0-9a-f]{2}){5}`

Now let's show that the match should capture all the text: start at the beginning and end at the end. That's done by wrapping the pattern in `pattern:^...$`.
Montrons maintenant que la correspondance se fait bien sur l'ensemble du texte : commence dès le début de la chaîne testée et termine à la fin. Cela se fait en entourant le motif de `pattern:^...$`.

Finally:
Finalement :

```js run
let regexp = /^[0-9a-f]{2}(:[0-9a-f]{2}){5}$/i;

alert( regexp.test('01:32:54:67:89:AB') ); // true

alert( regexp.test('0132546789AB') ); // false (no colons)
alert( regexp.test('0132546789AB') ); // false (pas de double point)

alert( regexp.test('01:32:54:67:89') ); // false (5 numbers, need 6)
alert( regexp.test('01:32:54:67:89') ); // false (5 nombres, au lieu de 6)

alert( regexp.test('01:32:54:67:89:ZZ') ) // false (ZZ in the end)
alert( regexp.test('01:32:54:67:89:ZZ') ) // false (ZZ à la fin)
```
16 changes: 8 additions & 8 deletions 9-regular-expressions/11-regexp-groups/01-test-mac/task.md
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
# Check MAC-address
# Vérification d'adresse MAC

[MAC-address](https://en.wikipedia.org/wiki/MAC_address) of a network interface consists of 6 two-digit hex numbers separated by a colon.
L'[addresse MAC](https://fr.wikipedia.org/wiki/Adresse_MAC) d'une interface réseau est constitué de 6 paires de nombres hexadécimaux séparées par un double point.

For instance: `subject:'01:32:54:67:89:AB'`.
Par exemple : `subject:'01:32:54:67:89:AB'`.

Write a regexp that checks whether a string is MAC-address.
Écrire une regexp qui vérifie qu'une chaîne de caractères soit bien une adresse MAC.

Usage:
Utilisation:
```js
let regexp = /your regexp/;

alert( regexp.test('01:32:54:67:89:AB') ); // true

alert( regexp.test('0132546789AB') ); // false (no colons)
alert( regexp.test('0132546789AB') ); // false (double point manquant)

alert( regexp.test('01:32:54:67:89') ); // false (5 numbers, must be 6)
alert( regexp.test('01:32:54:67:89') ); // false (5 paires, mais 6 attendues)

alert( regexp.test('01:32:54:67:89:ZZ') ) // false (ZZ at the end)
alert( regexp.test('01:32:54:67:89:ZZ') ) // false (ZZ à la fin)
```
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
A regexp to search 3-digit color `#abc`: `pattern:/#[a-f0-9]{3}/i`.
Une regexp pour chercher une couleur à trois chiffres `#abc`: `pattern:/#[a-f0-9]{3}/i`.

We can add exactly 3 more optional hex digits. We don't need more or less. The color has either 3 or 6 digits.
Nous pouvons y ajouter les 3 autres chiffres optionnels. Nous n'avons pas besoin de plus ou moins. La couleur a soit 3 ou 6 chiffres.

Let's use the quantifier `pattern:{1,2}` for that: we'll have `pattern:/#([a-f0-9]{3}){1,2}/i`.
Utilisons le quantificateur `pattern:{1,2}` pour obtenir `pattern:/#([a-f0-9]{3}){1,2}/i`.

Here the pattern `pattern:[a-f0-9]{3}` is enclosed in parentheses to apply the quantifier `pattern:{1,2}`.
Ici le schéma `pattern:[a-f0-9]{3}` est entouré de parenthèses pour lui appliquer le quantificateur `pattern:{1,2}`.

In action:
En pratique :

```js run
let regexp = /#([a-f0-9]{3}){1,2}/gi;
Expand All @@ -16,7 +16,7 @@ let str = "color: #3f3; background-color: #AA00ef; and: #abcd";
alert( str.match(regexp) ); // #3f3 #AA00ef #abc
```

There's a minor problem here: the pattern found `match:#abc` in `subject:#abcd`. To prevent that we can add `pattern:\b` to the end:
Il reste un petit problème ici : car ce schéma trouve `match:#abc` dans `subject:#abcd`. Pour éviter cela nous pouvons ajouter à la fin `pattern:\b` :

```js run
let regexp = /#([a-f0-9]{3}){1,2}\b/gi;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
# Find color in the format #abc or #abcdef
# Trouver des couleurs au format #abc ou #abcdef

Write a RegExp that matches colors in the format `#abc` or `#abcdef`. That is: `#` followed by 3 or 6 hexadecimal digits.
Écrire une RegExp qui correspond à des couleurs au format `#abc` ou `#abcdef`. C'est à dire : `#` suivi par 3 ou 6 chiffres hexadécimaux.

Usage example:
Exemple d'utilisation :
```js
let regexp = /your regexp/g;

Expand All @@ -11,4 +11,4 @@ let str = "color: #3f3; background-color: #AA00ef; and: #abcd";
alert( str.match(regexp) ); // #3f3 #AA00ef
```

P.S. This should be exactly 3 or 6 hex digits. Values with 4 digits, such as `#abcd`, should not match.
P.S. Cela doit être exactement 3 ou 6 chiffres. Des valeurs avec 4 chiffres, comme `#abcd`, ne doivent pas ressortir.
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
A positive number with an optional decimal part is: `pattern:\d+(\.\d+)?`.
Un nombre positif avec une éventuelle partie décimale correspond à : `pattern:\d+(\.\d+)?`.

Let's add the optional `pattern:-` in the beginning:
Ajoutons l'option `pattern:-` au début :

```js run
let regexp = /-?\d+(\.\d+)?/g;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
# Find all numbers
# Trouvez tous les nombres

Write a regexp that looks for all decimal numbers including integer ones, with the floating point and negative ones.
Écrire un regexp qui cherche tous les nombres décimaux, comprenant les entiers, les nombres décimaux avec le point comme séparateur et les nombres négatifs.

An example of use:
Un exemple d'utilisation :

```js
let regexp = /your regexp/g;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,44 +1,44 @@
A regexp for a number is: `pattern:-?\d+(\.\d+)?`. We created it in the previous task.
Une regexp pour un nombre : `pattern:-?\d+(\.\d+)?`. Nous l'avons vu dans l'exercice précédent.

An operator is `pattern:[-+*/]`. The hyphen `pattern:-` goes first in the square brackets, because in the middle it would mean a character range, while we just want a character `-`.
Pour l'opérateur `pattern:[-+*/]`. Le tiret `pattern:-` est en premier, car il pourrait signifier un intervalle de caractère, alors que nous souhaitons juste le caractère `-`.

The slash `/` should be escaped inside a JavaScript regexp `pattern:/.../`, we'll do that later.
Le slash `/` doit être échappé en javascript dans une regexp `pattern:/.../`, et nous le ferons plus tard.

We need a number, an operator, and then another number. And optional spaces between them.
Nous cherchons un nombre, un opérateur puis un autre nombre. Et d'éventuels espaces entre eux.

The full regular expression: `pattern:-?\d+(\.\d+)?\s*[-+*/]\s*-?\d+(\.\d+)?`.
Cela done l'expression régulière : `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.
Il y a trois parties, avec `pattern:\s*` entre elles :
1. `pattern:-?\d+(\.\d+)?` - le premier nombre,
1. `pattern:[-+*/]` - l'opérateur,
1. `pattern:-?\d+(\.\d+)?` - le deuxième nombre.

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+)?)`.
Pour faire de chacune de ces parties un élément distinct du tableau de correspondance, entourons-les de parenthèses : `pattern:(-?\d+(\.\d+)?)\s*([-+*/])\s*(-?\d+(\.\d+)?)`.

In action:
Cela donne :

```js run
let regexp = /(-?\d+(\.\d+)?)\s*([-+*\/])\s*(-?\d+(\.\d+)?)/;

alert( "1.2 + 12".match(regexp) );
```

The result includes:
Le résultat inclus :

- `result[0] == "1.2 + 12"` (full match)
- `result[1] == "1.2"` (first group `(-?\d+(\.\d+)?)` -- the first number, including the decimal part)
- `result[2] == ".2"` (second group`(\.\d+)?` -- the first decimal part)
- `result[3] == "+"` (third group `([-+*\/])` -- the operator)
- `result[4] == "12"` (forth group `(-?\d+(\.\d+)?)` -- the second number)
- `result[5] == undefined` (fifth group `(\.\d+)?` -- the last decimal part is absent, so it's undefined)
- `result[0] == "1.2 + 12"` (la correspondance complète)
- `result[1] == "1.2"` (premier groupe `(-?\d+(\.\d+)?)` -- le premier nombre, avec la partie décimale)
- `result[2] == ".2"` (second groupe`(\.\d+)?` -- la première partie décimale)
- `result[3] == "+"` (troisième groupe `([-+*\/])` -- l'opérateur)
- `result[4] == "12"` (quatrième groupe `(-?\d+(\.\d+)?)` -- le second nombre)
- `result[5] == undefined` (cinquième groupe `(\.\d+)?` -- la deuxième partie décimale est absente, c'est non défini)

We only want the numbers and the operator, without the full match or the decimal parts, so let's "clean" the result a bit.
Nous ne souhaitons que les nombres et l'opérateur, sans la correspondance entière, ni les parties décimales. Faisons alors un peu le ménage.

The full match (the arrays first item) can be removed by shifting the array `result.shift()`.
La correspondance complète(le premier élément du tableau) peut être enlevée par `result.shift()`.

Groups that contain decimal parts (number 2 and 4) `pattern:(.\d+)` can be excluded by adding `pattern:?:` to the beginning: `pattern:(?:\.\d+)?`.
Les groupes contenant les parties décimales(groupes 2 et 4) `pattern:(.\d+)` peuvent être exclus en ajoutant `pattern:?:` au début : `pattern:(?:\.\d+)?`.

The final solution:
La solution complète :

```js run
function parse(expr) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,23 +1,23 @@
# Parse an expression
# Parsez une expression

An arithmetical expression consists of 2 numbers and an operator between them, for instance:
Une expression arithmétique consiste en 2 nombres et un opérateur entre les deux, par exemple :

- `1 + 2`
- `1.2 * 3.4`
- `-3 / -6`
- `-2 - 2`

The operator is one of: `"+"`, `"-"`, `"*"` or `"/"`.
L'opérateur l'un des : `"+"`, `"-"`, `"*"` ou `"/"`.

There may be extra spaces at the beginning, at the end or between the parts.
Il peut y avoir des espaces supplémentaires au début, à la fin ou entre chaque partie.

Create a function `parse(expr)` that takes an expression and returns an array of 3 items:
Créez une fonction `parse(expr)` qui prend une expression et retourne un tableau de trois éléments :

1. The first number.
2. The operator.
3. The second number.
1. Le premier nombre.
2. L'opérateur.
3. Le second nombre.

For example:
Par exemple :

```js
let [a, op, b] = parse("1.2 * 3.4");
Expand Down
Loading