Skip to content

Commit 082f738

Browse files
authored
Merge pull request #308 from mrkrash/regular-expressions/sets-and-ranges
Sets and ranges
2 parents 9322fc5 + 94932f8 commit 082f738

File tree

5 files changed

+99
-98
lines changed

5 files changed

+99
-98
lines changed
Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,13 @@
1-
Answers: **no, yes**.
1+
Risposte: **no, sì**.
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+
- Nello script `subject:Java` non c'Γ¨ corrispondenza, dato che per `pattern:[^script]` si intende "qualunque carattere eccetto quelli dati". Quindi la regexp cerca `"Java"` seguito da uno di tali caratteri, ma c'Γ¨ la fine della stringa, non ci sono caratteri dopo di esso.
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+
- Sì, poiché `pattern:[^script]` trova il carattere `"S"` che non è uno di `pattern:script`. Considerato che la regexp fa distinzione tra maiuscole e minuscole (non c'è il flag `pattern:i`), tratta `"S"` come un carattere differente da `"s"`.
99
1010
```js run
1111
alert( "JavaScript".match(/Java[^script]/) ); // "JavaS"
1212
```
13+
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+
Abbiamo una regexp `pattern:/Java[^script]/`.
44

5-
Does it match anything in the string `subject:Java`? In the string `subject:JavaScript`?
5+
Cosa corrisponde nella stringa `subject:Java`? E nella stringa `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+
Risposta: `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+
Fate attenzione al fatto che il trattino `pattern:'-'` ha un significato speciale tra le parentesi quadre, ma solo tra gli altri caratteri, non quando Γ¨ all'inizio o alla fine, quindi non c'Γ¨ bisogno dell'escape.
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+
# Trova l'orario come hh:mm o 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'orario puΓ² essere nel formato `ore:minuti` o `ore-minuti`. Entrambi, ore e minuti, hanno 2 numeri: `09:00` o `21-30`.
44

5-
Write a regexp to find time:
5+
Scrivete una regexp per trovare l'orario:
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. In questo esercizio considereremo che l'orario Γ¨ sempre corretto, non c'Γ¨ necessitΓ  di filtrare stringhe come "45:67". PiΓΉ tardi ci occuperemo anche di questo tipo di problema.
Lines changed: 87 additions & 87 deletions
Original file line numberDiff line numberDiff line change
@@ -1,197 +1,197 @@
1-
# Sets and ranges [...]
1+
# Insiemi e intervalli [...]
22

3-
Several characters or character classes inside square brackets `[…]` mean to "search for any character among given".
3+
Alcuni caratteri o classi di caratteri inseriti all'interno di parantesi quadre `[…]` significano "cerca qualsiasi carattere tra quelli forniti".
44

5-
## Sets
5+
## Insiemi
66

7-
For instance, `pattern:[eao]` means any of the 3 characters: `'a'`, `'e'`, or `'o'`.
7+
Per esempio, `pattern:[eao]` significa uno qualunque dei 3 caratteri: `'a'`, `'e'`, od `'o'`.
88

9-
That's called a *set*. Sets can be used in a regexp along with regular characters:
9+
Questo Γ¨ chiamato un *insieme* o *set*. I set posso essere usati in una regexp insieme ad altri caratteri:
1010

1111
```js run
12-
// find [t or m], and then "op"
12+
// trova [t o m], e quindi "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+
Si noti che sebbene ci siano piΓΉ caratteri nel set, questi corrispondano esattamente a un carattere nel match.
1717

18-
So the example below gives no matches:
18+
Quindi il seguente esempio non dΓ  alcuna corrispondenza:
1919

2020
```js run
21-
// find "V", then [o or i], then "la"
22-
alert( "Voila".match(/V[oi]la/) ); // null, no matches
21+
// trova "V", poi ['o' o 'i'], quindi "la"
22+
alert( "Voila".match(/V[oi]la/) ); // null, nessuna corrispondenza
2323
```
2424

25-
The pattern searches for:
25+
Il modello di ricerca risulta quindi:
2626

2727
- `pattern:V`,
28-
- then *one* of the letters `pattern:[oi]`,
29-
- then `pattern:la`.
28+
- poi *una* di queste lettere `pattern:[oi]`,
29+
- quindi `pattern:la`.
3030

31-
So there would be a match for `match:Vola` or `match:Vila`.
31+
Significa che ci dovrebbe essere una corrispondenza per `match:Vola` o `match:Vila`.
3232

33-
## Ranges
33+
## Intervalli
3434

35-
Square brackets may also contain *character ranges*.
35+
Le parentesi quadre possono contenere anche *intervalli di caratteri*.
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+
Per esempio, `pattern:[a-z]` indica un carattere nell'intervallo che va da `a` a `z`, e `pattern:[0-5]` indica un numero tra `0` e `5`.
3838

39-
In the example below we're searching for `"x"` followed by two digits or letters from `A` to `F`:
39+
Nell'esempio seguente cercheremo una `"x"` seguita da due numeri o lettere da `A` 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+
Il modello `pattern:[0-9A-F]` ha due intervalli: cerca un carattere che sia una cifra da `0` a `9` o una lettera da `A` a `F`.
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+
Se volessimo cercare anche lettere minuscole, possiamo aggiungere l'intervallo `a-f`: `pattern:[0-9A-Fa-f]`, o aggiungere il flag `pattern:i`.
4848

49-
We can also use character classes inside `[…]`.
49+
Possiamo anche usare classi di caratteri dentro `[…]`.
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+
Per esempio, se volessimo cercare un carattere di parola `pattern:\w` o un trattino `pattern:-`, allora l'insieme sarΓ  `pattern:[\w-]`.
5252

53-
Combining multiple classes is also possible, e.g. `pattern:[\s\d]` means "a space character or a digit".
53+
È anche possibile combinare diverse classi, es `pattern:[\s\d]` significa "uno spazio o un numero".
5454

55-
```smart header="Character classes are shorthands for certain character sets"
56-
For instance:
55+
```smart header="Le classi di caratteri sono abbreviazioni per determinati set di caratteri"
56+
Per esempio:
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** -- Γ¨ la stessa cosa di `pattern:[0-9]`,
59+
- **\w** -- Γ¨ la stessa cosa di `pattern:[a-zA-Z0-9_]`,
60+
- **\s** -- Γ¨ la stessa cosa di `pattern:[\t\n\v\f\r ]` e pochi altri rari caratteri Unicode.
6161
```
6262

63-
### Example: multi-language \w
63+
### Esempio: multi lingua \w
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+
Dal momento che la classe di caratteri `pattern:\w` Γ¨ una scorciatoia per `pattern:[a-zA-Z0-9_]`, non puΓ² trovare geroglifici cinesi, lettere cirilliche, ecc.
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+
Possiamo allora scrivere un modello piΓΉ universale, che cerca un carattere di parola in qualunque lingua. Questo Γ¨ reso facile dalle proprietΓ  Unicode: `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+
Decifriamolo. Similarmente a `pattern:\w`, stiamo creando un nostro insieme che include i caratteri con le seguenti proprietΓ  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`) - per le lettere,
72+
- `Mark` (`M`) - per gli accenti,
73+
- `Decimal_Number` (`Nd`) - per i numeri,
74+
- `Connector_Punctuation` (`Pc`) - per il trattino basso `'_'` e caratteri simili,
75+
- `Join_Control` (`Join_C`) - due codici speciali `200c` e `200d`, usati nelle legature, a.e. in Arabo.
7676

77-
An example of use:
77+
Un esempio di utilizzo:
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+
// Trova tutte le lettere e i numeri:
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+
Naturalmente possiamo modificare questo modello: aggiungere proprietΓ  Unicode o rimuoverle. Le proprietΓ  Unicode sono descritte meglio nell'articolo <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="Le proprietΓ  Unicode non sono supportate da IE"
91+
Le proprietΓ  Unicode `pattern:p{…}` non sono implementate in IE. Se ne abbiamo davvero bisogno possiamo utilizzare la libreria [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+
In alternativa possiamo utilizzare soltanto un intervallo di caratteri nella lingua che ci interessa, a.e. `pattern:[а-я]` per le lettere cirilliche.
9494
```
9595

96-
## Excluding ranges
96+
## Esclusione di intervalli
9797

98-
Besides normal ranges, there are "excluding" ranges that look like `pattern:[^…]`.
98+
Oltre ai normali intervalli, Γ¨ possibile creare dei modelli di "esclusione", come `pattern:[^…]`.
9999

100-
They are denoted by a caret character `^` at the start and match any character *except the given ones*.
100+
Sono contraddistinti da un accento circonflesso `^` all'inizio e trovano corrispondenza in qualunque carattere *tranne quelli indicati*.
101101

102-
For instance:
102+
Per esempio:
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]` -- qualunque carattere tranne `'a'`, `'e'`, `'y'` o `'o'`.
105+
- `pattern:[^0-9]` -- qualunque carattere tranne un numero, come `pattern:\D`.
106+
- `pattern:[^\s]` -- qualunque carattere che non sia uno spazio, come `\S`.
107107

108-
The example below looks for any characters except letters, digits and spaces:
108+
L'esempio seguente cerca qualunque carattere eccetto lettere, numeri e spazi:
109109

110110
```js run
111-
alert( "alice15@gmail.com".match(/[^\d\sA-Z]/gi) ); // @ and .
111+
alert( "alice15@gmail.com".match(/[^\d\sA-Z]/gi) ); // @ e .
112112
```
113113

114-
## Escaping in […]
114+
## L'escape dentro […]
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+
In genere quando vogliamo trovare esattamente un carattere speciale, dobbiamo effettuarne l'escape: `pattern:\.`. Se abbiamo bisogno di un backslash, allora dobbiamo usare `pattern:\\`, e così via.
117117

118-
In square brackets we can use the vast majority of special characters without escaping:
118+
Dentro le parentesi quadre, possiamo usare la stragrande maggioranza di caratteri speciali senza la necessitΓ  di effettuarne l'escape:
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+
- I simboli `pattern:. + ( )` non necessitano mai di escaping.
121+
- Il trattino `pattern:-` non Γ¨ preceduto da caratteri di escape all'inizio o alla fine (dove non definisce un intervallo).
122+
- Un accento circonflesso `pattern:^` Γ¨ soggetto ad escape solo all'inizio (dove significa esclusione).
123+
- La parentesi quadra di chiusura `pattern:]` dev'essere sempre soggetta ad escape (se abbiamo bisogno di cercare questo simbolo).
124124

125-
In other words, all special characters are allowed without escaping, except when they mean something for square brackets.
125+
In altre parole, tutti i caratteri speciali sono consentiti senza necessitΓ  di escape, eccetto quando significano qualcosa all'interno delle parentesi quadre.
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 punto `.` all'interno delle parentesi quadre significa soltanto un punto. Il modello `pattern:[.,]` cercherebbe uno dei caratteri: o un punto o una virgola.
128128

129-
In the example below the regexp `pattern:[-().^+]` looks for one of the characters `-().^+`:
129+
Nell'esempio seguente la regexp `pattern:[-().^+]` effettua la ricerca per uno dei caratteri `-().^+`:
130130

131131
```js run
132-
// No need to escape
132+
// Non necessita di escape
133133
let regexp = /[-().^+]/g;
134134

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

138-
...But if you decide to escape them "just in case", then there would be no harm:
138+
...Ma se decidete di effettuare l'escape "per ogni evenienza", il risultato non cambierebbe:
139139

140140
```js run
141-
// Escaped everything
141+
// Escape di ogni carattere
142142
let regexp = /[\-\(\)\.\^\+]/g;
143143

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

147-
## Ranges and flag "u"
147+
## Intervalli e flag "u"
148148

149-
If there are surrogate pairs in the set, flag `pattern:u` is required for them to work correctly.
149+
Se ci sono coppie surrogate nel set, il flag `pattern:u` Γ¨ necessario affinchΓ© la ricerca funzioni correttamente.
150150

151-
For instance, let's look for `pattern:[𝒳𝒴]` in the string `subject:𝒳`:
151+
Per esempio, cerchiamo `pattern:[𝒳𝒴]` nella stringa `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(/[𝒳𝒴]/) ); // mostra uno strano carattere, come [?]
155+
// (la ricerca Γ¨ stata eseguita in modo errato, viene restituito mezzo-carattere)
156156
```
157157

158-
The result is incorrect, because by default regular expressions "don't know" about surrogate pairs.
158+
Il risultato non Γ¨ corretto, perchΓ© di base le espressioni regolari "non sanno nulla" riguardo le coppie surrogate.
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+
Il motore delle espressioni regolari pensa che `[𝒳𝒴]` -- non sono due, ma quattro caratteri:
161+
1. metΓ  alla sinistra di `𝒳` `(1)`,
162+
2. metΓ  alla destra di `𝒳` `(2)`,
163+
3. metΓ  alla sinistra di `𝒴` `(3)`,
164+
4. metΓ  alla destra di `𝒴` `(4)`.
165165

166-
We can see their codes like this:
166+
Possiamo vedere il suo codice in questo modo:
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+
Quini, l'esempio qui sopra trova e visualizza la metΓ  alla sinistra di `𝒳`.
175175

176-
If we add flag `pattern:u`, then the behavior will be correct:
176+
Se aggiungiamo il flag `pattern:u`, allora il comportamento sarΓ  corretto:
177177

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

182-
The similar situation occurs when looking for a range, such as `[𝒳-𝒴]`.
182+
Una situazione simile si verifica quando si cerca un intervallo, come `[𝒳-𝒴]`.
183183

184-
If we forget to add flag `pattern:u`, there will be an error:
184+
Se dimentichiamo di aggiungere il flag `pattern:u`, ci sarΓ  un errore:
185185

186186
```js run
187-
'𝒳'.match(/[𝒳-𝒴]/); // Error: Invalid regular expression
187+
'𝒳'.match(/[𝒳-𝒴]/); // Errore: 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+
La ragione Γ¨ che senza il flag `pattern:u` le coppie surrogate sono percepite come due caratteri, quindi `[𝒳-𝒴]` Γ¨ interpretato come `[<55349><56499>-<55349><56500>]` (ogni coppia surrogata Γ¨ sostituita con i suoi codici). Ora Γ¨ facile osservare che l'intervallo `56499-55349` non Γ¨ valido: il suo codice iniziale `56499` Γ¨ maggiore di quello finale `55349`. Questa Γ¨ la ragione formale dell'errore.
191191

192-
With the flag `pattern:u` the pattern works correctly:
192+
Con il flag `pattern:u` il modello funziona correttamente:
193193

194194
```js run
195-
// look for characters from 𝒳 to 𝒡
195+
// cerca i caratteri da 𝒳 a 𝒡
196196
alert( '𝒴'.match(/[𝒳-𝒡]/u) ); // 𝒴
197197
```

0 commit comments

Comments
Β (0)