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
The flag`pattern:y`allows to perform the search at the given position in the source string.
4
+
Le marqueur`pattern:y`permet d'effectuer la recherche à partir d'une position donnée dans la chaîne de caractères source.
5
5
6
-
To grasp the use case of `pattern:y` flag, and better understand the ways of regexps, let's explore a practical example.
6
+
Pour appréhender le cas d'usage du marqueur `pattern:y`, et mieux comprendre le fonctionnement des regexp, regardons un exemple pratique.
7
7
8
-
One of common tasks for regexps is "lexical analysis": we get a text, e.g. in a programming language, and need to find its structural elements. For instance, HTML has tags and attributes, JavaScript code has functions, variables, and so on.
8
+
Prenons un usage courant des regexps, l'analyse lexicale : Nous avons un texte, p. ex. dans un langage de programmation, et nous avons besoin de trouver ses éléments de structure. Par exemple, l'HTML a des balises et des attributs, du code JavaScript a des fonctions, variables, etc.
9
9
10
-
Writing lexical analyzers is a special area, with its own tools and algorithms, so we don't go deep in there, but there's a common task: to read something at the given position.
10
+
L'écriture d'analyseurs lexicaux est un domaine spécifique, avec ses propres outils et algorithmes que nous n'explorerons pas ici, mais il y a une tâche courante : Lire quelque chose depuis une position donnée.
11
11
12
-
E.g. we have a code string`subject:let varName = "value"`, and we need to read the variable name from it, that starts at position `4`.
12
+
P. ex. prenons la chaîne de caractères`subject:let varName = "value"`, dans laquelle nous devons lire le nom de la variable, qui commence à la position `4`.
13
13
14
-
We'll look for variable name using regexp `pattern:\w+`. Actually, JavaScript variable names need a bit more complex regexp for accurate matching, but here it doesn't matter.
14
+
Nous chercherons un nom de variable en utilisant la regexp `pattern:\w+`. En fait, les noms de variable en JavaScript nécessitent une regexp un poil plus complexe pour un résultat exact, mais cela est sans importance ici.
15
15
16
-
-A call to`str.match(/\w+/)`will find only the first word in the line (`let`). That's not it.
17
-
-We can add the flag`pattern:g`. But then the call`str.match(/\w+/g)`will look for all words in the text, while we need one word at position `4`. Again, not what we need.
16
+
-Un appel à`str.match(/\w+/)`trouvera seulement le premier mot de la ligne (`let`). Ça n'est pas ça.
17
+
-Nous pouvons ajouter le marqueur`pattern:g`. Mais alors l'appel à`str.match(/\w+/g)`cherchera tous les mots du text, alors que nous avons besoin que d'un mot à partir de la position `4`. Ça n'est pas encore ça.
18
18
19
-
**So, how to search for a regexp exactly at the given position?**
19
+
**Alors comment rechercher un motif à partir d'une position donné ?**
20
20
21
-
Let's try using method`regexp.exec(str)`.
21
+
Essayons en utilisant la méthode`regexp.exec(str)`.
22
22
23
-
For a`regexp`without flags`pattern:g`and`pattern:y`, this method looks only for the first match, it works exactly like`str.match(regexp)`.
23
+
Pour une`regexp`sans marqueur`pattern:g`ni`pattern:y`, cette méthode cherche seulement la première occurrence, cela fonctionne exactement comme`str.match(regexp)`.
24
24
25
-
...But if there's flag `pattern:g`, then it performs the search in`str`, starting from position stored in the`regexp.lastIndex` property. And, if it finds a match, then sets`regexp.lastIndex`to the index immediately after the match.
25
+
...Mais s'il y a le marqueur `pattern:g`, il effectue alors une recherche dans`str`, à partir de la position stockée dans propriété`regexp.lastIndex`. Et s'il trouve une correspondance, il fixe`regexp.lastIndex`à l'index immédiatement après la correspondance.
26
26
27
-
In other words, `regexp.lastIndex`serves as a starting point for the search, that each `regexp.exec(str)`call resets to the new value ("after the last match"). That's only if there's `pattern:g` flag, of course.
27
+
En d'autres termes, `regexp.lastIndex`sert de point de départ pour la recherche, que chaque appel à `regexp.exec(str)`change en une nouvelle valeur ("après la dernière correspondance"). Cela, bien entendu, seulement avec le marquer `pattern:g`.
28
28
29
-
So, successive calls to `regexp.exec(str)`return matches one after another.
29
+
Donc chaque appel successif à `regexp.exec(str)`retourne une correspondance après l'autre.
30
30
31
-
Here's an example of such calls:
31
+
Voici un exemple de tels appels :
32
32
33
33
```js run
34
-
let str ='let varName'; //Let's find all words in this string
34
+
let str ='let varName'; //Cherchons tous les mots dans cette chaîne de caractères
alert(regexp.lastIndex); // 0 (réinitialisé à la fin de la recherche)
50
50
```
51
51
52
-
We can get all matches in the loop:
52
+
Nous pouvons obtenir toutes les correspondances avec la boucle :
53
53
54
54
```js run
55
55
let str ='let varName';
@@ -59,23 +59,23 @@ let result;
59
59
60
60
while (result =regexp.exec(str)) {
61
61
alert( `Found ${result[0]} at position ${result.index}` );
62
-
// Found let at position 0, then
62
+
// Found let at position 0, puis
63
63
// Found varName at position 4
64
64
}
65
65
```
66
66
67
-
Such use of `regexp.exec`is an alternative to method `str.matchAll`, with a bit more control over the process.
67
+
Une telle utilisation de `regexp.exec`est une alternative à la méthode `str.matchAll`, avec un peu plus de contrôle sur le processus.
68
68
69
-
Let's go back to our task.
69
+
Retournons à notre objectif.
70
70
71
-
We can manually set`lastIndex`to `4`, to start the search from the given position!
71
+
Nous pouvons assigner à`lastIndex`la valeur `4`, pour commencer la recherche à partir de cette position!
72
72
73
-
Like this:
73
+
Comme ceci :
74
74
75
75
```js run
76
76
let str ='let varName = "value"';
77
77
78
-
let regexp =/\w+/g; //without flag "g", property lastIndex is ignored
78
+
let regexp =/\w+/g; //sans le marqueur "g", la propriété lastIndex est ignorée
79
79
80
80
*!*
81
81
regexp.lastIndex=4;
@@ -85,54 +85,54 @@ let word = regexp.exec(str);
85
85
alert(word); // varName
86
86
```
87
87
88
-
Hooray! Problem solved!
88
+
Houra ! Problème résolu !
89
89
90
-
We performed a search of`pattern:\w+`, starting from position `regexp.lastIndex = 4`.
90
+
Nous avons recherché le motif`pattern:\w+`, à partir de la position `regexp.lastIndex = 4`.
91
91
92
-
The result is correct.
92
+
Le résultat est valide.
93
93
94
-
...But wait, not so fast.
94
+
...Mais attendez, pas si vite.
95
95
96
-
Please note: the `regexp.exec`call starts searching at position `lastIndex`and then goes further. If there's no word at position `lastIndex`, but it's somewhere after it, then it will be found:
96
+
Vous noterez : l'appel à `regexp.exec`commence la recherche à la position `lastIndex`et continue ensuite plus loin. S'il n'y a pas de mot à la position `lastIndex`, mais qu'il y en a un plus loin, il sera alors trouvé :
97
97
98
98
```js run
99
99
let str ='let varName = "value"';
100
100
101
101
let regexp =/\w+/g;
102
102
103
103
*!*
104
-
//start the search from position 3
104
+
//comme la recherche à la position 3
105
105
regexp.lastIndex=3;
106
106
*/!*
107
107
108
108
let word =regexp.exec(str);
109
-
//found the match at position 4
109
+
//trouve la correspondance à la position 4
110
110
alert(word[0]); // varName
111
111
alert(word.index); // 4
112
112
```
113
113
114
-
For some tasks, including the lexical analysis, that's just wrong. We need to find a match exactly at the given position at the text, not somewhere after it. And that's what the flag `y` is for.
114
+
Pour certaines tâches, et pour les analyses lexicales en particulier, c'est juste faux. Nous avons besoin de trouver la correspondance du motif à la position exacte, et non quelque part après. Et c'est justement ce que fait le marqueur `y`.
115
115
116
-
**The flag`pattern:y`makes `regexp.exec`to search exactly at position `lastIndex`, not "starting from" it.**
116
+
**Le marqueur`pattern:y`fait que `regexp.exec`recherche exactement à la position `lastIndex`, et non à partir de cette position.**
117
117
118
-
Here's the same search with flag`pattern:y`:
118
+
Voici la même recherche avec le marqueur`pattern:y`:
119
119
120
120
```js run
121
121
let str ='let varName = "value"';
122
122
123
123
let regexp =/\w+/y;
124
124
125
125
regexp.lastIndex=3;
126
-
alert( regexp.exec(str) ); // null (there's a space at position 3, not a word)
126
+
alert( regexp.exec(str) ); // null (il n'y a pas de mot en position 3, mais un espace)
127
127
128
128
regexp.lastIndex=4;
129
-
alert( regexp.exec(str) ); // varName (word at position 4)
129
+
alert( regexp.exec(str) ); // varName (mot en position 4)
130
130
```
131
131
132
-
As we can see, regexp `pattern:/\w+/y`doesn't match at position `3` (unlike the flag`pattern:g`), but matches at position `4`.
132
+
Comme nous pouvons le voir, la regexp `pattern:/\w+/y`ne trouve pas de correspondance en position `3` (contrairement au marqueur`pattern:g`), mais trouve la correspondance en position `4`.
133
133
134
-
Not only that's what we need, there's an important performance gain when using flag`pattern:y`.
134
+
Et en plus d'obtenir ce que nous cherchions, mais il y a un gain significatif de performance avec le marqueur`pattern:y`.
135
135
136
-
Imagine, we have a long text, and there are no matches in it, at all. Then a search with flag`pattern:g`will go till the end of the text and find nothing, and this will take significantly more time than the search with flag `pattern:y`, that checks only the exact position.
136
+
Imaginez avec un long texte, et sans aucune correspondance dedans. Une recherche avec le marqueur`pattern:g`ira alors jusqu'à la fin du texte pour ne rien trouver, et cela prendra bien plus de temps qu'avec le marqueur `pattern:y`, qui vérifie seulement à la position exacte.
137
137
138
-
In tasks like lexical analysis, there are usually many searches at an exact position, to check what we have there. Using flag `pattern:y`is the key for correct implementations and a good performance.
138
+
Dans des tâches comme en analyse lexicale, il y a habituellement beaucoup de recherches sur des positions exactes, pour vérifier ce qu'il s'y trouve. L'utilisation du marqueur `pattern:y`est la clé pour des bonnes implémentations et de bonnes performances.
0 commit comments