Skip to content

Commit 21f039d

Browse files
committed
translate article from start to matchAll
1 parent e036f57 commit 21f039d

File tree

1 file changed

+80
-80
lines changed

1 file changed

+80
-80
lines changed

9-regular-expressions/11-regexp-groups/article.md

Lines changed: 80 additions & 80 deletions
Original file line numberDiff line numberDiff line change
@@ -1,84 +1,84 @@
1-
# Capturing groups
1+
# Groupes capturant
22

3-
A part of a pattern can be enclosed in parentheses `pattern:(...)`. This is called a "capturing group".
3+
Une partie de motif peut être entourée de parenthèses `pattern:(...)`. Cela s'appelle un "groupe capturant".
44

5-
That has two effects:
5+
Ceci a deux effets :
66

7-
1. It allows to get a part of the match as a separate item in the result array.
8-
2. If we put a quantifier after the parentheses, it applies to the parentheses as a whole.
7+
1. Cela permet d'obtenir cette partie de correspondance comme élément du tableau de résultat.
8+
2. Si nous mettons après les parenthèses un quantificateur, celui-ci s'applique à tout l'ensemble entre parenthèses.
99

10-
## Examples
10+
## Exemples
1111

12-
Let's see how parentheses work in examples.
12+
Voyons comment fonctionne le parenthésage par des exemples.
1313

14-
### Example: gogogo
14+
### Exemple : gogogo
1515

16-
Without parentheses, the pattern `pattern:go+` means `subject:g` character, followed by `subject:o` repeated one or more times. For instance, `match:goooo` or `match:gooooooooo`.
16+
Sans parenthèses, le motif `pattern:go+` signifie le caractère `subject:g`, suivi par `subject:o` répété une ou plusieurs fois. Par exemple, `match:goooo` ou `match:gooooooooo`.
1717

18-
Parentheses group characters together, so `pattern:(go)+` means `match:go`, `match:gogo`, `match:gogogo` and so on.
18+
Avec des parenthèses regroupant les caractères, `pattern:(go)+` signifie alors `match:go`, `match:gogo`, `match:gogogo` et ainsi de suite.
1919

2020
```js run
2121
alert( 'Gogogo now!'.match(/(go)+/ig) ); // "Gogogo"
2222
```
2323

24-
### Example: domain
24+
### Exemple : domaine
2525

26-
Let's make something more complex -- a regular expression to search for a website domain.
26+
Complexifions maintenant un peu les choses -- une expression régulière pour rechercher le domaine d'un site web.
2727

28-
For example:
28+
Par exemple :
2929

3030
```
3131
mail.com
3232
users.mail.com
3333
smith.users.mail.com
3434
```
3535

36-
As we can see, a domain consists of repeated words, a dot after each one except the last one.
36+
Comme nous pouvons le voir, un domaine est constitué d'une répétition de mots, un point après chaque mot excepté pour le dernier.
3737

38-
In regular expressions that's `pattern:(\w+\.)+\w+`:
38+
En expression régulière cela donne `pattern:(\w+\.)+\w+`:
3939

4040
```js run
4141
let regexp = /(\w+\.)+\w+/g;
4242

4343
alert( "site.com my.site.com".match(regexp) ); // site.com,my.site.com
4444
```
4545

46-
The search works, but the pattern can't match a domain with a hyphen, e.g. `my-site.com`, because the hyphen does not belong to class `pattern:\w`.
46+
La recherche fonctionne, mais ce motif ne correspondra pas à un domaine comportant un tiret, par ex. `my-site.com`, car le tiret n'appartient pas à la classe `pattern:\w`.
4747

48-
We can fix it by replacing `pattern:\w` with `pattern:[\w-]` in every word except the last one: `pattern:([\w-]+\.)+\w+`.
48+
Nous pouvons corriger ça en remplaçant `pattern:\w` par `pattern:[\w-]` pour tous les mots excepté le dernier : `pattern:([\w-]+\.)+\w+`.
4949

50-
### Example: email
50+
### Exemple : email
5151

52-
The previous example can be extended. We can create a regular expression for emails based on it.
52+
En se basant sur l'exemple précédent, nous pouvons créer une expression régulière pour les emails.
5353

54-
The email format is: `name@domain`. Any word can be the name, hyphens and dots are allowed. In regular expressions that's `pattern:[-.\w]+`.
54+
Le format d'un email est : `nom@domaine`. Le nom peut comporter n'importe quel mot, tirets et points sont permis. En expression régulière cela donne `pattern:[-.\w]+`.
5555

56-
The pattern:
56+
Le motif :
5757

5858
```js run
5959
let regexp = /[-.\w]+@([\w-]+\.)+[\w-]+/g;
6060

6161
alert("my@mail.com @ his@site.com.uk".match(regexp)); // my@mail.com, his@site.com.uk
6262
```
6363

64-
That regexp is not perfect, but mostly works and helps to fix accidental mistypes. The only truly reliable check for an email can only be done by sending a letter.
64+
Cette regexp loin d'être parfaite, fonctionne dans une majorité de cas et aide à corriger d'éventuelles fautes de frappes. La seule vérification fiable à 100% pour un email est effectuée par l'envoi d'un courrier.
6565

66-
## Parentheses contents in the match
66+
## Contenus des parenthèses dans la correspondance
6767

68-
Parentheses are numbered from left to right. The search engine memorizes the content matched by each of them and allows to get it in the result.
68+
Les parenthèses sont numérotées de gauche à droite. Le moteur de recherche mémorise le contenu correspondant à chacune d'entre elles et permet d'y accéder dans le résultat.
6969

70-
The method `str.match(regexp)`, if `regexp` has no flag `g`, looks for the first match and returns it as an array:
70+
La méthode `str.match(regexp)`, si `regexp` n'a pas de marqueur `g`, cherche la première correspondance et la retourne dans un tableau :
7171

72-
1. At index `0`: the full match.
73-
2. At index `1`: the contents of the first parentheses.
74-
3. At index `2`: the contents of the second parentheses.
75-
4. ...and so on...
72+
1. À l'index `0`: la correspondance complète.
73+
2. À l'index `1`: le contenu des premières parenthèses.
74+
3. À l'index `2`: le contenu des secondes parenthèses.
75+
4. ...etc...
7676

77-
For instance, we'd like to find HTML tags `pattern:<.*?>`, and process them. It would be convenient to have tag content (what's inside the angles), in a separate variable.
77+
Par exemple, si nous voulons trouver des balises HTML `pattern:<.*?>`, et agir dessus. Cela peut être pratique d'en avoir le contenu (l'intérieur des chevrons), dans des variables distinctes.
7878

79-
Let's wrap the inner content into parentheses, like this: `pattern:<(.*?)>`.
79+
Entourons l'intérieur de la balise de parenthèses, comme ceci : `pattern:<(.*?)>`.
8080

81-
Now we'll get both the tag as a whole `match:<h1>` and its contents `match:h1` in the resulting array:
81+
Et nous aurons maintenant à la fois la balise entière `match:<h1>` et son contenu `match:h1` dans le tableau de correspondance :
8282

8383
```js run
8484
let str = '<h1>Hello, world!</h1>';
@@ -89,23 +89,23 @@ alert( tag[0] ); // <h1>
8989
alert( tag[1] ); // h1
9090
```
9191

92-
### Nested groups
92+
### Groupes imbriqués
9393

94-
Parentheses can be nested. In this case the numbering also goes from left to right.
94+
Les parenthèses peuvent être imbriquées. Dans ce cas la numérotation se fait aussi de gauche à droite.
9595

96-
For instance, when searching a tag in `subject:<span class="my">` we may be interested in:
96+
Par exemple, en effectuant une recherche dans la balise `subject:<span class="my">` nous pourrions est intéressé par :
9797

98-
1. The tag content as a whole: `match:span class="my"`.
99-
2. The tag name: `match:span`.
100-
3. The tag attributes: `match:class="my"`.
98+
1. Son contenu complet : `match:span class="my"`.
99+
2. Son nom : `match:span`.
100+
3. Ses attributs : `match:class="my"`.
101101

102-
Let's add parentheses for them: `pattern:<(([a-z]+)\s*([^>]*))>`.
102+
Ajoutons-leur des parenthèses : `pattern:<(([a-z]+)\s*([^>]*))>`.
103103

104-
Here's how they are numbered (left to right, by the opening paren):
104+
Voici comment ils sont numérotés (gauche à droite, par ordre d'ouverture) :
105105

106106
![](regexp-nested-groups-pattern.svg)
107107

108-
In action:
108+
En action:
109109

110110
```js run
111111
let str = '<span class="my">';
@@ -119,59 +119,59 @@ alert(result[2]); // span
119119
alert(result[3]); // class="my"
120120
```
121121

122-
The zero index of `result` always holds the full match.
122+
L'index zero de `result` contient toujours l'entière correspondance.
123123

124-
Then groups, numbered from left to right by an opening paren. The first group is returned as `result[1]`. Here it encloses the whole tag content.
124+
Puis les groupes, numérotés de gauche à droite par ordre d'ouverture des parenthèses. Le premier groupe est retourné comme `result[1]`. Il enferme ici tout le contenu de la balise.
125125

126-
Then in `result[2]` goes the group from the second opening paren `pattern:([a-z]+)` - tag name, then in `result[3]` the tag: `pattern:([^>]*)`.
126+
Puis dans `result[2]` se trouve le groupe de la deuxième parenthèse ouvrante `pattern:([a-z]+)` - le nom de balise, puis dans `result[3]` la suite de la balise : `pattern:([^>]*)`.
127127

128-
The contents of every group in the string:
128+
Les contenus de chaque groupe dans la chaîne de caractères :
129129

130130
![](regexp-nested-groups-matches.svg)
131131

132-
### Optional groups
132+
### Groupes optionnels
133133

134-
Even if a group is optional and doesn't exist in the match (e.g. has the quantifier `pattern:(...)?`), the corresponding `result` array item is present and equals `undefined`.
134+
Même si un groupe est optionnel et n'existe pas dans la correspondance (par ex. s'il a le quantificateur `pattern:(...)?`), son élément correspondant dans le tableau `result` est présent and vaut `undefined`.
135135

136-
For instance, let's consider the regexp `pattern:a(z)?(c)?`. It looks for `"a"` optionally followed by `"z"` optionally followed by `"c"`.
136+
Par exemple, considérons l'expression régulière `pattern:a(z)?(c)?`. Cela cherche un `"a"` suivi d'un éventuel `"z"` suivi d'un éventuel `"c"`.
137137

138-
If we run it on the string with a single letter `subject:a`, then the result is:
138+
Si nous lançons une recherche sur la seule lettre `subject:a`, alors le résultat donne:
139139

140140
```js run
141141
let match = 'a'.match(/a(z)?(c)?/);
142142

143143
alert( match.length ); // 3
144-
alert( match[0] ); // a (whole match)
144+
alert( match[0] ); // a (correspondance complète)
145145
alert( match[1] ); // undefined
146146
alert( match[2] ); // undefined
147147
```
148148

149-
The array has the length of `3`, but all groups are empty.
149+
Le tableau a une longueur de `3`, mais tous les groupes sont vides.
150150

151-
And here's a more complex match for the string `subject:ac`:
151+
Et voici une correspondance plus complexe pour la chaîne `subject:ac`:
152152

153153
```js run
154154
let match = 'ac'.match(/a(z)?(c)?/)
155155

156156
alert( match.length ); // 3
157-
alert( match[0] ); // ac (whole match)
158-
alert( match[1] ); // undefined, because there's nothing for (z)?
157+
alert( match[0] ); // ac (correspondance complète)
158+
alert( match[1] ); // undefined, car il n'y a rien pour (z)?
159159
alert( match[2] ); // c
160160
```
161161

162-
The array length is permanent: `3`. But there's nothing for the group `pattern:(z)?`, so the result is `["ac", undefined, "c"]`.
162+
La longueur du tableau fixe : `3`. Mais il n'y a rien pour le groupe `pattern:(z)?`, donc le résultat est `["ac", undefined, "c"]`.
163163

164-
## Searching for all matches with groups: matchAll
164+
## Rechercher toutes les correspondances avec des groupes : matchAll
165165

166-
```warn header="`matchAll` is a new method, polyfill may be needed"
167-
The method `matchAll` is not supported in old browsers.
166+
```warn header="`matchAll` est une méthode récente, et peut nécessiter un polyfill"
167+
La méthode `matchAll` n'est pas supporté par d'anciens navigateurs.
168168

169-
A polyfill may be required, such as <https://github.com/ljharb/String.prototype.matchAll>.
169+
Un polyfill peut être requis, comme <https://github.com/ljharb/String.prototype.matchAll>.
170170
```
171171
172-
When we search for all matches (flag `pattern:g`), the `match` method does not return contents for groups.
172+
Lorsque nous recherchons toutes les correspondances (flag `pattern:g`), la méthode `match` ne retourne pas le contenu des groupes.
173173
174-
For example, let's find all tags in a string:
174+
Par exemple, trouvons toutes les balises dans une chaîne de caractères:
175175
176176
```js run
177177
let str = '<h1> <h2>';
@@ -181,24 +181,24 @@ let tags = str.match(/<(.*?)>/g);
181181
alert( tags ); // <h1>,<h2>
182182
```
183183

184-
The result is an array of matches, but without details about each of them. But in practice we usually need contents of capturing groups in the result.
184+
Le résultat est un tableau de correspondance, mais sans les détails de chacune d'entre elles. Mais en pratique nous avons souvent besoin des contenus des groupes capturant dans le résultat.
185185

186-
To get them, we should search using the method `str.matchAll(regexp)`.
186+
Pour les obtenir, nous devons rechercher avec la méthode `str.matchAll(regexp)`.
187187

188-
It was added to JavaScript language long after `match`, as its "new and improved version".
188+
Elle a été ajoutée au language JavaScript longtemps après `match`, comme étant sa "version nouvelle et améliorée".
189189

190-
Just like `match`, it looks for matches, but there are 3 differences:
190+
Tout comme `match`, elle cherche des correspondances, mais avec 3 différences :
191191

192-
1. It returns not an array, but an iterable object.
193-
2. When the flag `pattern:g` is present, it returns every match as an array with groups.
194-
3. If there are no matches, it returns not `null`, but an empty iterable object.
192+
1. Elle ne retourne pas de tableau, mais un itérateur.
193+
2. Si le marqueur `pattern:g` est present, elle retourne toutes les correspondances en tableau avec les groupes.
194+
3. S'il n'y a pas de correspondance, elle ne retourne pas `null`, mais un itérateur vide.
195195

196-
For instance:
196+
Par exemple :
197197

198198
```js run
199199
let results = '<h1> <h2>'.matchAll(/<(.*?)>/gi);
200200

201-
// results - is not an array, but an iterable object
201+
// results - n'est pas un tableau, mais un itérateur
202202
alert(results); // [object RegExp String Iterator]
203203

204204
alert(results[0]); // undefined (*)
@@ -209,27 +209,27 @@ alert(results[0]); // <h1>,h1 (1st tag)
209209
alert(results[1]); // <h2>,h2 (2nd tag)
210210
```
211211

212-
As we can see, the first difference is very important, as demonstrated in the line `(*)`. We can't get the match as `results[0]`, because that object isn't pseudoarray. We can turn it into a real `Array` using `Array.from`. There are more details about pseudoarrays and iterables in the article <info:iterable>.
212+
Comme nous pouvons le voir, la première différence est très importante, comme le montre la ligne `(*)`. Nous ne pouvons pas trouver la correspondance dans `results[0]`, car il ne se comporte pas comme un tableau. Nous pouvons le convertir en véritable `Array` avec `Array.from`. Il y a plus de détails sur les objets itérables dans l'article <info:iterable>.
213213

214-
There's no need in `Array.from` if we're looping over results:
214+
Il n'y a pas besoin de `Array.from` si nous bouclons sur le résultat :
215215

216216
```js run
217217
let results = '<h1> <h2>'.matchAll(/<(.*?)>/gi);
218218

219219
for(let result of results) {
220220
alert(result);
221-
// first alert: <h1>,h1
221+
// premier alert: <h1>,h1
222222
// second: <h2>,h2
223223
}
224224
```
225225

226-
...Or using destructuring:
226+
...Ou bien en déstructurant :
227227

228228
```js
229229
let [tag1, tag2] = '<h1> <h2>'.matchAll(/<(.*?)>/gi);
230230
```
231231

232-
Every match, returned by `matchAll`, has the same format as returned by `match` without flag `pattern:g`: it's an array with additional properties `index` (match index in the string) and `input` (source string):
232+
Chaque correspondance, retournée par `matchAll`, a le même format que celui d'un `match` sans marqueur `pattern:g`: c'est un tableau avec les propriétés additionnelles `index` (index de la correspondance dans la chaîne) et `input` (chaîne source) :
233233

234234
```js run
235235
let results = '<h1> <h2>'.matchAll(/<(.*?)>/gi);
@@ -242,14 +242,14 @@ alert( tag1.index ); // 0
242242
alert( tag1.input ); // <h1> <h2>
243243
```
244244

245-
```smart header="Why is a result of `matchAll` an iterable object, not an array?"
246-
Why is the method designed like that? The reason is simple - for the optimization.
245+
```smart header="Pourquoi le résultat d'un `matchAll` un itérateur, et pas un tableau ?"
246+
Pourquoi la méthode est-elle conçue comme cela ? La raison est simple - pour l'optimisation.
247247

248-
The call to `matchAll` does not perform the search. Instead, it returns an iterable object, without the results initially. The search is performed each time we iterate over it, e.g. in the loop.
248+
L'appel à `matchAll` n'effectue pas la recherche. À la place, il retourne un itérateur, sans résultats préalables. La recherche est lancée à chaque fois que nous l'itérons, par ex. dans une boucle.
249249

250-
So, there will be found as many results as needed, not more.
250+
Ne seront donc trouvés qu'autant de résultats que besoin, pas plus.
251251

252-
E.g. there are potentially 100 matches in the text, but in a `for..of` loop we found 5 of them, then decided it's enough and made a `break`. Then the engine won't spend time finding other 95 matches.
252+
Par ex. il y a 100 correspondances potentielles dans un texte, mais dans une boucle `for..of` nous en trouvons 5, et décidons alors que c'est suffisant et faisons un `break`. Le moteur de recherche ne perdra pas son temps à rechercher les 95 autres correspondances.
253253
```
254254
255255
## Named groups

0 commit comments

Comments
 (0)