Skip to content

Commit b981378

Browse files
authored
Merge pull request #276 from XyoloJR/regex8
Sets and ranges [...]
2 parents 3afd48a + b4043ac commit b981378

File tree

5 files changed

+97
-97
lines changed

5 files changed

+97
-97
lines changed

9-regular-expressions/08-regexp-character-sets-and-ranges/1-find-range-1/solution.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
1-
Answers: **no, yes**.
1+
Réponses : **non, oui**.
22

3-
- In the script `subject:Java` it doesn't match anything, because `pattern:[^script]` means "any character except given ones". So the regexp looks for `"Java"` followed by one such symbol, but there's a string end, no symbols after it.
3+
- Dans la chaîne de caractères `subject:Java`, elle ne trouve aucune correspondance, parce que `pattern:[^script]` signifie "n'importe quel caractère sauf ceux cités". L'expression rationnelle cherche donc `"Java"` suivi d'un autre symbole, mais arrivant en fin de chaîne, elle n'en trouve aucun.
44

55
```js run
66
alert( "Java".match(/Java[^script]/) ); // null
77
```
8-
- Yes, because the `pattern:[^script]` part matches the character `"S"`. It's not one of `pattern:script`. As the regexp is case-sensitive (no `pattern:i` flag), it treats `"S"` as a different character from `"s"`.
8+
- Oui, car la partie `pattern:[^script]` correspond au caractère `"S"`. Qui n'est pas l'un des caractères de `pattern:script`. Comme l'expression rationnelle est sensible à la casse (pas de marqueur `pattern:i`), elle considère bien `"S"` différemment de `"s"`.
99
1010
```js run
1111
alert( "JavaScript".match(/Java[^script]/) ); // "JavaS"
Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
# Java[^script]
22

3-
We have a regexp `pattern:/Java[^script]/`.
3+
Considérons l'expression rationnelle `pattern:/Java[^script]/`.
44

5-
Does it match anything in the string `subject:Java`? In the string `subject:JavaScript`?
5+
Trouve-t-elle quelque chose dans la chaîne de caractères `subject:Java`? Dans la chaîne `subject:JavaScript`?
Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
1-
Answer: `pattern:\d\d[-:]\d\d`.
1+
Réponse : `pattern:\d\d[-:]\d\d`.
22

33
```js run
44
let regexp = /\d\d[-:]\d\d/g;
55
alert( "Breakfast at 09:00. Dinner at 21-30".match(regexp) ); // 09:00, 21-30
66
```
77

8-
Please note that the dash `pattern:'-'` has a special meaning in square brackets, but only between other characters, not when it's in the beginning or at the end, so we don't need to escape it.
8+
A noter que `pattern:'-'` à un sens particulier entre crochet, mais seulement entre deux autres caractères, et pas lorsqu'il débute ou termine l'ensemble, nous n'avons donc pas besoin de l'échapper ici.
Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
1-
# Find the time as hh:mm or hh-mm
1+
# Trouvez l'heure sous forme hh:mm ou hh-mm
22

3-
The time can be in the format `hours:minutes` or `hours-minutes`. Both hours and minutes have 2 digits: `09:00` or `21-30`.
3+
L'heure peut être au format `hours:minutes` ou `hours-minutes`. Les nombres "hours" et "minutes" sont composées de deux chiffres : `09:00` ou `21-30`.
44

5-
Write a regexp to find time:
5+
Écrire une expression rationnelle pour trouver l'heure quelle que soit sa forme :
66

77
```js
88
let regexp = /your regexp/g;
99
alert( "Breakfast at 09:00. Dinner at 21-30".match(regexp) ); // 09:00, 21-30
1010
```
1111

12-
P.S. In this task we assume that the time is always correct, there's no need to filter out bad strings like "45:67". Later we'll deal with that too.
12+
P.S. Dans cet exercice, on considère n'importe quelle heure comme valide, il n'y a pas besoin d'exclure une heure comme "45:67" par exemple. Nous nous occuperons de cela plus tard.
Lines changed: 86 additions & 86 deletions
Original file line numberDiff line numberDiff line change
@@ -1,197 +1,197 @@
1-
# Sets and ranges [...]
1+
# Ensembles et intervalles [...]
22

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à".
44

5-
## Sets
5+
## Ensembles
66

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'`.
88

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 :
1010

1111
```js run
12-
// find [t or m], and then "op"
12+
// trouve [t ou m], puis "op"
1313
alert( "Mop top".match(/[tm]op/gi) ); // "Mop", "top"
1414
```
1515

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.
1717

18-
So the example below gives no matches:
18+
L'exemple suivant ne donne donc aucun résultat :
1919

2020
```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
2323
```
2424

25-
The pattern searches for:
25+
L'expression régulière recherche :
2626

2727
- `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`.
3030

31-
So there would be a match for `match:Vola` or `match:Vila`.
31+
Ce qui correspondrait à `match:Vola` ou `match:Vila`.
3232

33-
## Ranges
33+
## Intervalles
3434

35-
Square brackets may also contain *character ranges*.
35+
Les crochets peuvent aussi contenir des *intervalles de caractères*.
3636

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`.
3838

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`:
4040

4141
```js run
4242
alert( "Exception 0xAF".match(/x[0-9A-F][0-9A-F]/g) ); // xAF
4343
```
4444

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.
4646

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`.
4848

49-
We can also use character classes inside `[…]`.
49+
Nous pouvons aussi utiliser les classes de caractères entre `[…]`.
5050

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-]`.
5252

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".
5454

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:
5757
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.
6161
```
6262

63-
### Example: multi-language \w
63+
### Exemple : \w multi-langue
6464

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.
6666

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}]`.
6868

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 :
7070

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.
7676

77-
An example of use:
77+
Exemple d'usage :
7878

7979
```js run
8080
let regexp = /[\p{Alpha}\p{M}\p{Nd}\p{Pc}\p{Join_C}]/gu;
8181

8282
let str = `Hi 你好 12`;
8383

84-
// finds all letters and digits:
84+
// trouve toutes les lettres et chiffres:
8585
alert( str.match(regexp) ); // H,i,你,好,1,2
8686
```
8787

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>.
8989

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/).
9292
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.
9494
```
9595

96-
## Excluding ranges
96+
## Intervalles d'exclusion
9797

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:[^…]`.
9999

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*.
101101

102-
For instance:
102+
Par exemple :
103103

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`.
107107

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 :
109109

110110
```js run
111-
alert( "[email protected]".match(/[^\d\sA-Z]/gi) ); // @ and .
111+
alert( "[email protected]".match(/[^\d\sA-Z]/gi) ); // @ et .
112112
```
113113

114-
## Escaping in []
114+
## L'échappement entre []
115115

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.
117117

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 :
119119

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).
124124

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.
126126

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.
128128

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 `-().^+`:
130130

131131
```js run
132-
// No need to escape
132+
// Pas besoin d'échapper
133133
let regexp = /[-().^+]/g;
134134

135-
alert( "1 + 2 - 3".match(regexp) ); // Matches +, -
135+
alert( "1 + 2 - 3".match(regexp) ); // trouve +, -
136136
```
137137

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 :
139139

140140
```js run
141-
// Escaped everything
141+
// Tout échappé
142142
let regexp = /[\-\(\)\.\^\+]/g;
143143

144-
alert( "1 + 2 - 3".match(regexp) ); // also works: +, -
144+
alert( "1 + 2 - 3".match(regexp) ); // fonctionne aussi: +, -
145145
```
146146

147-
## Ranges and flag "u"
147+
## Intervalles et marqueur "u"
148148

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.
150150

151-
For instance, let's look for `pattern:[𝒳𝒴]` in the string `subject:𝒳`:
151+
Par exemple, cherchons `pattern:[𝒳𝒴]` dans la chaîne `subject:𝒳`:
152152

153153
```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)
156156
```
157157

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.
159159

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)`.
165165

166-
We can see their codes like this:
166+
On peut voir le code de ces caractères ainsi :
167167

168168
```js run
169169
for(let i=0; i<'𝒳𝒴'.length; i++) {
170170
alert('𝒳𝒴'.charCodeAt(i)); // 55349, 56499, 55349, 56500
171171
};
172172
```
173173

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 `𝒳`.
175175

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 :
177177

178178
```js run
179179
alert( '𝒳'.match(/[𝒳𝒴]/u) ); // 𝒳
180180
```
181181

182-
The similar situation occurs when looking for a range, such as `[𝒳-𝒴]`.
182+
On retrouve un mécanisme similaire dans les intervalles, comme `[𝒳-𝒴]`.
183183

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 :
185185

186186
```js run
187187
'𝒳'.match(/[𝒳-𝒴]/); // Error: Invalid regular expression
188188
```
189189

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.
191191

192-
With the flag `pattern:u` the pattern works correctly:
192+
Avec le marqueur `pattern:u` le motif est interprété correctement :
193193

194194
```js run
195-
// look for characters from 𝒳 to 𝒵
195+
// Cherche un caractère entre 𝒳 et 𝒵 compris
196196
alert( '𝒴'.match(/[𝒳-𝒵]/u) ); // 𝒴
197197
```

0 commit comments

Comments
 (0)