|
1 |
| -# Sets and ranges [...] |
| 1 | +# Ensembles et intervalles [...] |
2 | 2 |
|
3 |
| -Several characters or character classes inside square brackets `[…]` mean to "search for any character among given". |
| 3 | +Plusieurs caractères ou classes de caractères, entourés de crochets `[…]` signifient "chercher un caractère parmi ceux-là". |
4 | 4 |
|
5 |
| -## Sets |
| 5 | +## Ensembles |
6 | 6 |
|
7 |
| -For instance, `pattern:[eao]` means any of the 3 characters: `'a'`, `'e'`, or `'o'`. |
| 7 | +Par exemple, `pattern:[eao]` signifie un caractère qui est soit `'a'`, `'e'`, ou `'o'`. |
8 | 8 |
|
9 |
| -That's called a *set*. Sets can be used in a regexp along with regular characters: |
| 9 | +On appelle cela un *ensemble*. Les ensembles peuvent être combinés avec d'autres caractères dans une même expression régulière : |
10 | 10 |
|
11 | 11 | ```js run
|
12 |
| -// find [t or m], and then "op" |
| 12 | +// trouve [t ou m], puis "op" |
13 | 13 | alert( "Mop top".match(/[tm]op/gi) ); // "Mop", "top"
|
14 | 14 | ```
|
15 | 15 |
|
16 |
| -Please note that although there are multiple characters in the set, they correspond to exactly one character in the match. |
| 16 | +Bien qu'il y ait plusieurs caractères dans un ensemble, vous remarquez que l'on ne cherche la correspondance que d'un seul de ces caractères. |
17 | 17 |
|
18 |
| -So the example below gives no matches: |
| 18 | +L'exemple suivant ne donne donc aucun résultat : |
19 | 19 |
|
20 | 20 | ```js run
|
21 |
| -// find "V", then [o or i], then "la" |
22 |
| -alert( "Voila".match(/V[oi]la/) ); // null, no matches |
| 21 | +// trouve "V", puis [o ou i], puis "la" |
| 22 | +alert( "Voila".match(/V[oi]la/) ); // null, pas de correspondance |
23 | 23 | ```
|
24 | 24 |
|
25 |
| -The pattern searches for: |
| 25 | +L'expression régulière recherche : |
26 | 26 |
|
27 | 27 | - `pattern:V`,
|
28 |
| -- then *one* of the letters `pattern:[oi]`, |
29 |
| -- then `pattern:la`. |
| 28 | +- puis *une* des lettres `pattern:[oi]`, |
| 29 | +- enfin `pattern:la`. |
30 | 30 |
|
31 |
| -So there would be a match for `match:Vola` or `match:Vila`. |
| 31 | +Ce qui correspondrait à `match:Vola` ou `match:Vila`. |
32 | 32 |
|
33 |
| -## Ranges |
| 33 | +## Intervalles |
34 | 34 |
|
35 |
| -Square brackets may also contain *character ranges*. |
| 35 | +Les crochets peuvent aussi contenir des *intervalles de caractères*. |
36 | 36 |
|
37 |
| -For instance, `pattern:[a-z]` is a character in range from `a` to `z`, and `pattern:[0-5]` is a digit from `0` to `5`. |
| 37 | +Par exemple, `pattern:[a-z]` est un caractère pouvant aller de `a` à `z`, et `pattern:[0-5]` est un chiffre allant de `0` à `5`. |
38 | 38 |
|
39 |
| -In the example below we're searching for `"x"` followed by two digits or letters from `A` to `F`: |
| 39 | +Dans l'exemple ci-dessous nous recherchons un `"x"` suivi par deux chiffres ou lettres de `A` à `F`: |
40 | 40 |
|
41 | 41 | ```js run
|
42 | 42 | alert( "Exception 0xAF".match(/x[0-9A-F][0-9A-F]/g) ); // xAF
|
43 | 43 | ```
|
44 | 44 |
|
45 |
| -Here `pattern:[0-9A-F]` has two ranges: it searches for a character that is either a digit from `0` to `9` or a letter from `A` to `F`. |
| 45 | +Ici `pattern:[0-9A-F]` comporte deux intervalles : il recherche un caractère qui est soit chiffre entre `0` et `9` compris ou bien une lettre entre `A` et `F` comprise. |
46 | 46 |
|
47 |
| -If we'd like to look for lowercase letters as well, we can add the range `a-f`: `pattern:[0-9A-Fa-f]`. Or add the flag `pattern:i`. |
| 47 | +Si nous voulons y inclure les lettres minuscules, nous pouvons ajouter l'intervalle `a-f`: `pattern:[0-9A-Fa-f]`. Ou bien ajouter le marqueur `pattern:i`. |
48 | 48 |
|
49 |
| -We can also use character classes inside `[…]`. |
| 49 | +Nous pouvons aussi utiliser les classes de caractères entre `[…]`. |
50 | 50 |
|
51 |
| -For instance, if we'd like to look for a wordly character `pattern:\w` or a hyphen `pattern:-`, then the set is `pattern:[\w-]`. |
| 51 | +Par exemple, si nous voulons chercher un caractère alphanumérique, un trait de soulignement `pattern:\w` ou un tiret `pattern:-`, alors l'ensemble s'écrit `pattern:[\w-]`. |
52 | 52 |
|
53 |
| -Combining multiple classes is also possible, e.g. `pattern:[\s\d]` means "a space character or a digit". |
| 53 | +Il est aussi possible de combiner plusieurs classes, p. ex. `pattern:[\s\d]` signifie "un caractère d'espacement ou un chiffre". |
54 | 54 |
|
55 |
| -```smart header="Character classes are shorthands for certain character sets" |
56 |
| -For instance: |
| 55 | +```smart header="Les classes de caractères sont en fait des racourcis pour des intervalles de caractères particuliers" |
| 56 | +Par exemple: |
57 | 57 |
|
58 |
| -- **\d** -- is the same as `pattern:[0-9]`, |
59 |
| -- **\w** -- is the same as `pattern:[a-zA-Z0-9_]`, |
60 |
| -- **\s** -- is the same as `pattern:[\t\n\v\f\r ]`, plus few other rare Unicode space characters. |
| 58 | +- **\d** -- équivaut à `pattern:[0-9]`, |
| 59 | +- **\w** -- équivaut à `pattern:[a-zA-Z0-9_]`, |
| 60 | +- **\s** -- équivaut à `pattern:[\t\n\v\f\r ]`, plus quelques autres rares caractères unicodes d'espacement. |
61 | 61 | ```
|
62 | 62 |
|
63 |
| -### Example: multi-language \w |
| 63 | +### Exemple : \w multi-langue |
64 | 64 |
|
65 |
| -As the character class `pattern:\w` is a shorthand for `pattern:[a-zA-Z0-9_]`, it can't find Chinese hieroglyphs, Cyrillic letters, etc. |
| 65 | +Comme la classe de caractères `pattern:\w` est un raccourci pour `pattern:[a-zA-Z0-9_]`, il ne peut pas trouver les idéogrammes chinois, ni les lettres cyrilliques, etc. |
66 | 66 |
|
67 |
| -We can write a more universal pattern, that looks for wordly characters in any language. That's easy with Unicode properties: `pattern:[\p{Alpha}\p{M}\p{Nd}\p{Pc}\p{Join_C}]`. |
| 67 | +Nous pouvons écrire un motif plus universel, pour rechercher le caractère d'un mot quelle que soit la langue. Grâce aux propriétés Unicode, on obtient facilement : `pattern:[\p{Alpha}\p{M}\p{Nd}\p{Pc}\p{Join_C}]`. |
68 | 68 |
|
69 |
| -Let's decipher it. Similar to `pattern:\w`, we're making a set of our own that includes characters with following Unicode properties: |
| 69 | +Déchiffrons cela. Tout comme `pattern:\w`, nous construisons notre propre ensemble qui contient les caractères qui portent les propriétés Unicode : |
70 | 70 |
|
71 |
| -- `Alphabetic` (`Alpha`) - for letters, |
72 |
| -- `Mark` (`M`) - for accents, |
73 |
| -- `Decimal_Number` (`Nd`) - for digits, |
74 |
| -- `Connector_Punctuation` (`Pc`) - for the underscore `'_'` and similar characters, |
75 |
| -- `Join_Control` (`Join_C`) - two special codes `200c` and `200d`, used in ligatures, e.g. in Arabic. |
| 71 | +- `Alphabetic` (`Alpha`) - pour les lettres, |
| 72 | +- `Mark` (`M`) - pour les accents, |
| 73 | +- `Decimal_Number` (`Nd`) - pour les nombres, |
| 74 | +- `Connector_Punctuation` (`Pc`) - pour le trait de soulignement `'_'` et autres caractères similaires, |
| 75 | +- `Join_Control` (`Join_C`) - deux codes spéciaux `200c` et `200d`, utilisés comme liaisons, p. ex. en arabe. |
76 | 76 |
|
77 |
| -An example of use: |
| 77 | +Exemple d'usage : |
78 | 78 |
|
79 | 79 | ```js run
|
80 | 80 | let regexp = /[\p{Alpha}\p{M}\p{Nd}\p{Pc}\p{Join_C}]/gu;
|
81 | 81 |
|
82 | 82 | let str = `Hi 你好 12`;
|
83 | 83 |
|
84 |
| -// finds all letters and digits: |
| 84 | +// trouve toutes les lettres et chiffres: |
85 | 85 | alert( str.match(regexp) ); // H,i,你,好,1,2
|
86 | 86 | ```
|
87 | 87 |
|
88 |
| -Of course, we can edit this pattern: add Unicode properties or remove them. Unicode properties are covered in more details in the article <info:regexp-unicode>. |
| 88 | +Cet ensemble est bien sûr encore modifiable : on peut y ajouter ou retirer des propriétés Unicode. Plus de détail sur ces propriétés Unicode dans l'article <info:regexp-unicode>. |
89 | 89 |
|
90 |
| -```warn header="Unicode properties aren't supported in IE" |
91 |
| -Unicode properties `pattern:p{…}` are not implemented in IE. If we really need them, we can use library [XRegExp](http://xregexp.com/). |
| 90 | +```warn header="Les propriétés Unicode ne sont pas supportées par IE" |
| 91 | +Les propriétés Unicode `pattern:p{…}` ne sont pas implémentées dans IE. Si nous en avons vraiment besoin, nous pouvons utiliser la librairie [XRegExp](http://xregexp.com/). |
92 | 92 |
|
93 |
| -Or just use ranges of characters in a language that interests us, e.g. `pattern:[а-я]` for Cyrillic letters. |
| 93 | +Ou simplement utiliser des intervalles de caractères dans la langue qui nous intéresse, p. ex. `pattern:[а-я]` pour les lettres cyrilliques. |
94 | 94 | ```
|
95 | 95 |
|
96 |
| -## Excluding ranges |
| 96 | +## Intervalles d'exclusion |
97 | 97 |
|
98 |
| -Besides normal ranges, there are "excluding" ranges that look like `pattern:[^…]`. |
| 98 | +En plus des intervalles classiques, il existe des intervalles d'exclusion de la forme `pattern:[^…]`. |
99 | 99 |
|
100 |
| -They are denoted by a caret character `^` at the start and match any character *except the given ones*. |
| 100 | +Ils se distinguent par un premier accent circonflexe `^` et correspond à n'importe quel caractère *à l'exception de ceux contenus dans ces crochets*. |
101 | 101 |
|
102 |
| -For instance: |
| 102 | +Par exemple : |
103 | 103 |
|
104 |
| -- `pattern:[^aeyo]` -- any character except `'a'`, `'e'`, `'y'` or `'o'`. |
105 |
| -- `pattern:[^0-9]` -- any character except a digit, the same as `pattern:\D`. |
106 |
| -- `pattern:[^\s]` -- any non-space character, same as `\S`. |
| 104 | +- `pattern:[^aeyo]` -- n'importe quel caractère sauf `'a'`, `'e'`, `'y'` ou `'o'`. |
| 105 | +- `pattern:[^0-9]` -- n'importe quel caractère à l'exception des chiffres, équivalent à `pattern:\D`. |
| 106 | +- `pattern:[^\s]` -- tout caractère qui n'est pas un espacement, équivalent à `\S`. |
107 | 107 |
|
108 |
| -The example below looks for any characters except letters, digits and spaces: |
| 108 | +L'exemple ci-dessous cherche n'importe quel caractère n'étant pas une lettre, un chiffre ou un espace : |
109 | 109 |
|
110 | 110 | ```js run
|
111 |
| -alert( "[email protected]". match( /[^\d\sA-Z]/gi) ); // @ and . |
| 111 | +alert( "[email protected]". match( /[^\d\sA-Z]/gi) ); // @ et . |
112 | 112 | ```
|
113 | 113 |
|
114 |
| -## Escaping in […] |
| 114 | +## L'échappement entre […] |
115 | 115 |
|
116 |
| -Usually when we want to find exactly a special character, we need to escape it like `pattern:\.`. And if we need a backslash, then we use `pattern:\\`, and so on. |
| 116 | +Habituellement, lorsque nous cherchons précisément un caractère spécial, nous devons l'échapper `pattern:\.`. Et si nous cherchons un backslash, nous utilisons `pattern:\\`, etc. |
117 | 117 |
|
118 |
| -In square brackets we can use the vast majority of special characters without escaping: |
| 118 | +À l'intérieur de crochets nous pouvons utiliser une grande majorité des caractères spéciaux sans échappement : |
119 | 119 |
|
120 |
| -- Symbols `pattern:. + ( )` never need escaping. |
121 |
| -- A hyphen `pattern:-` is not escaped in the beginning or the end (where it does not define a range). |
122 |
| -- A caret `pattern:^` is only escaped in the beginning (where it means exclusion). |
123 |
| -- The closing square bracket `pattern:]` is always escaped (if we need to look for that symbol). |
| 120 | +- Les symbols `pattern:. + ( )` ne sont jamais échappés. |
| 121 | +- Un tiret `pattern:-` n'est pas échappé en début ou fin d'ensemble (là où il ne peut pas définir d'intervalle). |
| 122 | +- Un accent circonflexe `pattern:^` est échappé uniquement s'il débute l'ensemble (sinon il signifie l'exclusion). |
| 123 | +- Le crochet fermant `pattern:]` est toujours échappé (si nous le cherchons précisément). |
124 | 124 |
|
125 |
| -In other words, all special characters are allowed without escaping, except when they mean something for square brackets. |
| 125 | +En d'autres termes, tous les caractères spéciaux ne sont pas échappés, sauf s'ils ont un sens particulier pour un ensemble. |
126 | 126 |
|
127 |
| -A dot `.` inside square brackets means just a dot. The pattern `pattern:[.,]` would look for one of characters: either a dot or a comma. |
| 127 | +Un point `.` à l'intérieur de crochets signifie juste un point. Le motif `pattern:[.,]` recherche un caractère : soit un point soit une virgule. |
128 | 128 |
|
129 |
| -In the example below the regexp `pattern:[-().^+]` looks for one of the characters `-().^+`: |
| 129 | +Dans l'exemple ci-dessous l'expression régulière `pattern:[-().^+]` cherche un des caractères `-().^+`: |
130 | 130 |
|
131 | 131 | ```js run
|
132 |
| -// No need to escape |
| 132 | +// Pas besoin d'échapper |
133 | 133 | let regexp = /[-().^+]/g;
|
134 | 134 |
|
135 |
| -alert( "1 + 2 - 3".match(regexp) ); // Matches +, - |
| 135 | +alert( "1 + 2 - 3".match(regexp) ); // trouve +, - |
136 | 136 | ```
|
137 | 137 |
|
138 |
| -...But if you decide to escape them "just in case", then there would be no harm: |
| 138 | +... Si vous décidez de les échapper, "au cas où", il n'y aura de toute façon aucun d'impact : |
139 | 139 |
|
140 | 140 | ```js run
|
141 |
| -// Escaped everything |
| 141 | +// Tout échappé |
142 | 142 | let regexp = /[\-\(\)\.\^\+]/g;
|
143 | 143 |
|
144 |
| -alert( "1 + 2 - 3".match(regexp) ); // also works: +, - |
| 144 | +alert( "1 + 2 - 3".match(regexp) ); // fonctionne aussi: +, - |
145 | 145 | ```
|
146 | 146 |
|
147 |
| -## Ranges and flag "u" |
| 147 | +## Intervalles et marqueur "u" |
148 | 148 |
|
149 |
| -If there are surrogate pairs in the set, flag `pattern:u` is required for them to work correctly. |
| 149 | +S'il y a une paire de seizets d'indirection([surrogate pair](https://fr.wikipedia.org/wiki/Table_des_caract%C3%A8res_Unicode_(D000-DFFF))) dans l'ensemble, le marqueur `pattern:u` est requis pour qu'elle soit interprétée correctement. |
150 | 150 |
|
151 |
| -For instance, let's look for `pattern:[𝒳𝒴]` in the string `subject:𝒳`: |
| 151 | +Par exemple, cherchons `pattern:[𝒳𝒴]` dans la chaîne `subject:𝒳`: |
152 | 152 |
|
153 | 153 | ```js run
|
154 |
| -alert( '𝒳'.match(/[𝒳𝒴]/) ); // shows a strange character, like [?] |
155 |
| -// (the search was performed incorrectly, half-character returned) |
| 154 | +alert( '𝒳'.match(/[𝒳𝒴]/) ); // affiche un caractère étrange qui ressemble à [?] |
| 155 | +// (la recherche n'a pas fonctionné correctement, seule une moitié du caractère est retournée) |
156 | 156 | ```
|
157 | 157 |
|
158 |
| -The result is incorrect, because by default regular expressions "don't know" about surrogate pairs. |
| 158 | +Le résultat n'est pas celui attendu, car par défaut une expression régulière ne reconnait pas une telle paire. |
159 | 159 |
|
160 |
| -The regular expression engine thinks that `[𝒳𝒴]` -- are not two, but four characters: |
161 |
| -1. left half of `𝒳` `(1)`, |
162 |
| -2. right half of `𝒳` `(2)`, |
163 |
| -3. left half of `𝒴` `(3)`, |
164 |
| -4. right half of `𝒴` `(4)`. |
| 160 | +Le moteur d'expression régulière pense que `[𝒳𝒴]` -- ne sont pas deux mais quatre caractères : |
| 161 | +1. la moitié gauche de `𝒳` `(1)`, |
| 162 | +2. la moitié droite de `𝒳` `(2)`, |
| 163 | +3. la moitié gauche de `𝒴` `(3)`, |
| 164 | +4. la moitié droite de `𝒴` `(4)`. |
165 | 165 |
|
166 |
| -We can see their codes like this: |
| 166 | +On peut voir le code de ces caractères ainsi : |
167 | 167 |
|
168 | 168 | ```js run
|
169 | 169 | for(let i=0; i<'𝒳𝒴'.length; i++) {
|
170 | 170 | alert('𝒳𝒴'.charCodeAt(i)); // 55349, 56499, 55349, 56500
|
171 | 171 | };
|
172 | 172 | ```
|
173 | 173 |
|
174 |
| -So, the example above finds and shows the left half of `𝒳`. |
| 174 | +Donc, le premier exemple trouve et affiche la première moitié de `𝒳`. |
175 | 175 |
|
176 |
| -If we add flag `pattern:u`, then the behavior will be correct: |
| 176 | +Mais si nous ajoutons le marqueur `pattern:u`, on aura alors le comportement attendu : |
177 | 177 |
|
178 | 178 | ```js run
|
179 | 179 | alert( '𝒳'.match(/[𝒳𝒴]/u) ); // 𝒳
|
180 | 180 | ```
|
181 | 181 |
|
182 |
| -The similar situation occurs when looking for a range, such as `[𝒳-𝒴]`. |
| 182 | +On retrouve un mécanisme similaire dans les intervalles, comme `[𝒳-𝒴]`. |
183 | 183 |
|
184 |
| -If we forget to add flag `pattern:u`, there will be an error: |
| 184 | +Si nous oublions le marqueur `pattern:u`, il y aura une erreur : |
185 | 185 |
|
186 | 186 | ```js run
|
187 | 187 | '𝒳'.match(/[𝒳-𝒴]/); // Error: Invalid regular expression
|
188 | 188 | ```
|
189 | 189 |
|
190 |
| -The reason is that without flag `pattern:u` surrogate pairs are perceived as two characters, so `[𝒳-𝒴]` is interpreted as `[<55349><56499>-<55349><56500>]` (every surrogate pair is replaced with its codes). Now it's easy to see that the range `56499-55349` is invalid: its starting code `56499` is greater than the end `55349`. That's the formal reason for the error. |
| 190 | +En effet sans le marqueur `pattern:u` une paire de seizets est perçue comme deux caractères distincts, donc `[𝒳-𝒴]` est interprété en `[<55349><56499>-<55349><56500>]` (chacune des paires est remplacée par ses codes). Il est maintenant évident que l'intervalle `56499-55349` n'est pas valide : le premier code `56499` est plus grand que le dernier `55349`. Ce qui explique l'erreur précédente. |
191 | 191 |
|
192 |
| -With the flag `pattern:u` the pattern works correctly: |
| 192 | +Avec le marqueur `pattern:u` le motif est interprété correctement : |
193 | 193 |
|
194 | 194 | ```js run
|
195 |
| -// look for characters from 𝒳 to 𝒵 |
| 195 | +// Cherche un caractère entre 𝒳 et 𝒵 compris |
196 | 196 | alert( '𝒴'.match(/[𝒳-𝒵]/u) ); // 𝒴
|
197 | 197 | ```
|
0 commit comments