You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: 9-regular-expressions/11-regexp-groups/article.md
+80-80Lines changed: 80 additions & 80 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,84 +1,84 @@
1
-
# Capturing groups
1
+
# Groupes capturant
2
2
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".
4
4
5
-
That has two effects:
5
+
Ceci a deux effets :
6
6
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.
9
9
10
-
## Examples
10
+
## Exemples
11
11
12
-
Let's see how parentheses work in examples.
12
+
Voyons comment fonctionne le parenthésage par des exemples.
13
13
14
-
### Example: gogogo
14
+
### Exemple : gogogo
15
15
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`.
17
17
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.
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`.
47
47
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+`.
49
49
50
-
### Example: email
50
+
### Exemple : email
51
51
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.
53
53
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]+`.
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.
65
65
66
-
## Parentheses contents in the match
66
+
## Contenus des parenthèses dans la correspondance
67
67
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.
69
69
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 :
71
71
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...
76
76
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.
78
78
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:<(.*?)>`.
80
80
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 :
82
82
83
83
```js run
84
84
let str ='<h1>Hello, world!</h1>';
@@ -89,23 +89,23 @@ alert( tag[0] ); // <h1>
89
89
alert( tag[1] ); // h1
90
90
```
91
91
92
-
### Nested groups
92
+
### Groupes imbriqués
93
93
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.
95
95
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 :
97
97
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"`.
101
101
102
-
Let's add parentheses for them: `pattern:<(([a-z]+)\s*([^>]*))>`.
102
+
Ajoutons-leur des parenthèses : `pattern:<(([a-z]+)\s*([^>]*))>`.
103
103
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) :
105
105
106
106

107
107
108
-
In action:
108
+
En action:
109
109
110
110
```js run
111
111
let str ='<span class="my">';
@@ -119,59 +119,59 @@ alert(result[2]); // span
119
119
alert(result[3]); // class="my"
120
120
```
121
121
122
-
The zero index of `result`always holds the full match.
122
+
L'index zero de `result`contient toujours l'entière correspondance.
123
123
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.
125
125
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:([^>]*)`.
127
127
128
-
The contents of every group in the string:
128
+
Les contenus de chaque groupe dans la chaîne de caractères :
129
129
130
130

131
131
132
-
### Optional groups
132
+
### Groupes optionnels
133
133
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`.
135
135
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"`.
137
137
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:
139
139
140
140
```js run
141
141
let match ='a'.match(/a(z)?(c)?/);
142
142
143
143
alert( match.length ); // 3
144
-
alert( match[0] ); // a (whole match)
144
+
alert( match[0] ); // a (correspondance complète)
145
145
alert( match[1] ); // undefined
146
146
alert( match[2] ); // undefined
147
147
```
148
148
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.
150
150
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`:
152
152
153
153
```js run
154
154
let match ='ac'.match(/a(z)?(c)?/)
155
155
156
156
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)?
159
159
alert( match[2] ); // c
160
160
```
161
161
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"]`.
163
163
164
-
## Searching for all matches with groups: matchAll
164
+
## Rechercher toutes les correspondances avec des groupes : matchAll
165
165
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.
168
168
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>.
170
170
```
171
171
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.
173
173
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:
175
175
176
176
```js run
177
177
let str = '<h1> <h2>';
@@ -181,24 +181,24 @@ let tags = str.match(/<(.*?)>/g);
181
181
alert( tags ); // <h1>,<h2>
182
182
```
183
183
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.
185
185
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)`.
187
187
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".
189
189
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 :
191
191
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.
195
195
196
-
For instance:
196
+
Par exemple :
197
197
198
198
```js run
199
199
let results ='<h1> <h2>'.matchAll(/<(.*?)>/gi);
200
200
201
-
// results - is not an array, but an iterable object
201
+
// results - n'est pas un tableau, mais un itérateur
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>.
213
213
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 :
215
215
216
216
```js run
217
217
let results ='<h1> <h2>'.matchAll(/<(.*?)>/gi);
218
218
219
219
for(let result of results) {
220
220
alert(result);
221
-
//first alert: <h1>,h1
221
+
//premier alert: <h1>,h1
222
222
// second: <h2>,h2
223
223
}
224
224
```
225
225
226
-
...Or using destructuring:
226
+
...Ou bien en déstructurant :
227
227
228
228
```js
229
229
let [tag1, tag2] ='<h1> <h2>'.matchAll(/<(.*?)>/gi);
230
230
```
231
231
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) :
233
233
234
234
```js run
235
235
let results ='<h1> <h2>'.matchAll(/<(.*?)>/gi);
@@ -242,14 +242,14 @@ alert( tag1.index ); // 0
242
242
alert( tag1.input ); // <h1> <h2>
243
243
```
244
244
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.
247
247
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.
249
249
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.
251
251
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.
0 commit comments