Skip to content

Commit 8241bee

Browse files
authored
Merge pull request #46 from eadensplace/unicode-flag-u
Unicode: flag "u" and class \p{...}
2 parents 444822f + 30c3818 commit 8241bee

File tree

2 files changed

+73
-73
lines changed

2 files changed

+73
-73
lines changed

9-regular-expressions/20-regexp-unicode/article.md

Lines changed: 31 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,88 +1,88 @@
11

22
# Unicode: flag "u"
33

4-
The unicode flag `/.../u` enables the correct support of surrogate pairs.
4+
La flag unicode `/.../u` abilita il corretto supporto delle coppie surrogate.
55

6-
Surrogate pairs are explained in the chapter <info:string>.
6+
Le coppie surrogate sono spiegate nel capitolo <info:string>.
77

8-
Let's briefly review them here. In short, normally characters are encoded with 2 bytes. That gives us 65536 characters maximum. But there are more characters in the world.
8+
Rivediamole brevemente qui. In poche parole, i caratteri normali sono codificati con 2 byte. Questo ci dà un massimo di 65536 caratteri. Ma ci sono più caratteri nel mondo.
99

10-
So certain rare characters are encoded with 4 bytes, like `𝒳` (mathematical X) or `😄` (a smile).
10+
Quindi alcuni caratteri più rari sono codificati con 4 byte, come `𝒳` (la X matematica) o `😄` (uno smile).
1111

12-
Here are the unicode values to compare:
12+
Qui vi sono i valori unicode da comparare:
1313

14-
| Character | Unicode | Bytes |
14+
| Carattere | Unicode | Byte |
1515
|------------|---------|--------|
1616
| `a` | 0x0061 | 2 |
1717
| `` | 0x2248 | 2 |
1818
|`𝒳`| 0x1d4b3 | 4 |
1919
|`𝒴`| 0x1d4b4 | 4 |
2020
|`😄`| 0x1f604 | 4 |
2121

22-
So characters like `a` and `` occupy 2 bytes, and those rare ones take 4.
22+
Dunque caratteri come `a` e `` occupano 2 bytes, e quelli rari ne occupano 4.
2323

24-
The unicode is made in such a way that the 4-byte characters only have a meaning as a whole.
24+
Unicode è stato fatto in modo tale che i caratteri a 4 byte abbiano un significato solo considerando l'intero insieme.
2525

26-
In the past JavaScript did not know about that, and many string methods still have problems. For instance, `length` thinks that here are two characters:
26+
In precedenza JavaScript non ne sapeva nulla, e molti metodi delle stringhe ancora presentano problemi. Per esempio, `length` pensa che qui ci siano due caratteri:
2727

2828
```js run
2929
alert('😄'.length); // 2
3030
alert('𝒳'.length); // 2
3131
```
3232

33-
...But we can see that there's only one, right? The point is that `length` treats 4 bytes as two 2-byte characters. That's incorrect, because they must be considered only together (so-called "surrogate pair").
33+
...Ma possiamo vedere che ce n'è solo uno, giusto? Il punto è che `length` tratta i caratteri a 4 byte come due caratteri a 2-byte. Questo non è corretto, perché devono essere considerati solo insieme (per cui chiamati "coppie surrogate").
3434

35-
Normally, regular expressions also treat "long characters" as two 2-byte ones.
35+
Usualmente, anche le espressioni regolari trattano questi "caratteri lunghi" come due caratteri a 2-byte.
3636

37-
That leads to odd results, for instance let's try to find `pattern:[𝒳𝒴]` in the string `subject:𝒳`:
37+
Questo porta a strani risultati, ad esempio proviamo a cercare `pattern:[𝒳𝒴]` nella stringa `subject:𝒳`:
3838

3939
```js run
40-
alert( '𝒳'.match(/[𝒳𝒴]/) ); // odd result (wrong match actually, "half-character")
40+
alert( '𝒳'.match(/[𝒳𝒴]/) ); // risultato strano (in realtà è una corrispondenza errata, "mezzo carattere")
4141
```
4242

43-
The result is wrong, because by default the regexp engine does not understand surrogate pairs.
43+
Il risultato è errato, perché di default il motore delle regexp non comprende le coppie surrogate.
4444

45-
So, it thinks that `[𝒳𝒴]` are not two, but four characters:
46-
1. the left half of `𝒳` `(1)`,
47-
2. the right half of `𝒳` `(2)`,
48-
3. the left half of `𝒴` `(3)`,
49-
4. the right half of `𝒴` `(4)`.
45+
Dunque, pensa che `[𝒳𝒴]` non siano due, ma quattro caratteri:
46+
1. la metà sinistra di `𝒳` `(1)`,
47+
2. la metà destra di `𝒳` `(2)`,
48+
3. la metà sinistra di `𝒴` `(3)`,
49+
4. la metà destra di `𝒴` `(4)`.
5050

51-
We can list them like this:
51+
Li possiamo elencare così:
5252

5353
```js run
5454
for(let i=0; i<'𝒳𝒴'.length; i++) {
5555
alert('𝒳𝒴'.charCodeAt(i)); // 55349, 56499, 55349, 56500
5656
};
5757
```
5858

59-
So it finds only the "left half" of `𝒳`.
59+
Quindi trova solo la "metà sinistra" di `𝒳`.
6060

61-
In other words, the search works like `'12'.match(/[1234]/)`: only `1` is returned.
61+
In altre parole, la ricerca funziona come `'12'.match(/[1234]/)`: solo `1` viene restituito.
6262

63-
## The "u" flag
63+
## La flag "u"
6464

65-
The `/.../u` flag fixes that.
65+
La flag `/.../u` risolve questo problema.
6666

67-
It enables surrogate pairs in the regexp engine, so the result is correct:
67+
Essa abilita le coppie surrogate nel motore delle regexp, in modo tale che il risultato sia:
6868

6969
```js run
7070
alert( '𝒳'.match(/[𝒳𝒴]/u) ); // 𝒳
7171
```
7272

73-
Let's see one more example.
73+
Vediamo un altro esempio.
7474

75-
If we forget the `u` flag and occasionally use surrogate pairs, then we can get an error:
75+
Se dimentichiamo la flag `u` e occasionalmente usiamo le coppie surrogate, possiamo incorrere in errori:
7676

7777
```js run
78-
'𝒳'.match(/[𝒳-𝒴]/); // SyntaxError: invalid range in character class
78+
'𝒳'.match(/[𝒳-𝒴]/); // SyntaxError: intervallo non valido nella classe di caratteri
7979
```
8080

81-
Normally, regexps understand `[a-z]` as a "range of characters with codes between codes of `a` and `z`.
81+
Di solito, le regexp interpretano `[a-z]` come un "intervallo di caratteri con codici tra `a` e `z`.
8282

83-
But without `u` flag, surrogate pairs are assumed to be a "pair of independent characters", so `[𝒳-𝒴]` is like `[<55349><56499>-<55349><56500>]` (replaced each surrogate pair with code points). Now we can clearly see that the range `56499-55349` is unacceptable, as the left range border must be less than the right one.
83+
Ma senza la flag `u`, le coppie surrogate vengono interpretate come "coppie di caratteri indipendenti", quindi `[𝒳-𝒴]` è come `[<55349><56499>-<55349><56500>]` (sostituito a ogni coppia surrogata il codice corrispondente). Ora possiamo vedere con più chiarezza che l'intervallo `56499-55349` non è accettabile, dato che il valore a sinistra dell'intervallo deve essere inferiore rispetto a quello a destra.
8484

85-
Using the `u` flag makes it work right:
85+
Usando la flag `u` tutto funziona di nuovo:
8686

8787
```js run
8888
alert( '𝒴'.match(/[𝒳-𝒵]/u) ); // 𝒴

9-regular-expressions/21-regexp-unicode-properties/article.md

Lines changed: 42 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -1,81 +1,81 @@
11

2-
# Unicode character properties \p
2+
# Proprietà dei caratteri Unicode \p
33

4-
[Unicode](https://en.wikipedia.org/wiki/Unicode), the encoding format used by JavaScript strings, has a lot of properties for different characters (or, technically, code points). They describe which "categories" character belongs to, and a variety of technical details.
4+
[Unicode](https://en.wikipedia.org/wiki/Unicode), il formato di codifica usato dalle stringhe di JavaScript, ha molte proprietà per diversi caratteri. Esse descrivono a quali "categorie" appartiene il carattere, e una varietà di dettagli tecnici.
55

6-
In regular expressions these can be set by `\p{…}`. And there must be flag `'u'`.
6+
Nelle espressioni regolari queste possono essere impostate con `\p{…}`. E deve esserci la flag `'u'`.
77

8-
For instance, `\p{Letter}` denotes a letter in any of language. We can also use `\p{L}`, as `L` is an alias of `Letter`, there are shorter aliases for almost every property.
8+
Per esempio, `\p{Letter}` indica una lettera in qualsiasi lingua. Possiamo anche usare `\p{L}`, o `L` al posto di `Letter`, ci sono alias più corti quasi per tutte le proprietà.
99

10-
Here's the main tree of properties:
10+
Qui c'è l'albero principale delle proprietà:
1111

12-
- Letter `L`:
13-
- lowercase `Ll`, modifier `Lm`, titlecase `Lt`, uppercase `Lu`, other `Lo`
14-
- Number `N`:
15-
- decimal digit `Nd`, letter number `Nl`, other `No`
16-
- Punctuation `P`:
17-
- connector `Pc`, dash `Pd`, initial quote `Pi`, final quote `Pf`, open `Ps`, close `Pe`, other `Po`
18-
- Mark `M` (accents etc):
19-
- spacing combining `Mc`, enclosing `Me`, non-spacing `Mn`
20-
- Symbol `S`:
21-
- currency `Sc`, modifier `Sk`, math `Sm`, other `So`
22-
- Separator `Z`:
23-
- line `Zl`, paragraph `Zp`, space `Zs`
24-
- Other `C`:
25-
- control `Cc`, format `Cf`, not assigned `Cn`, private use `Co`, surrogate `Cs`
12+
- Lettera `L`:
13+
- minuscolo `Ll`, modificatore `Lm`, titolo `Lt`, maiuscolo `Lu`, altro `Lo`
14+
- Numero `N`:
15+
- cifra decimale `Nd`, numero letterale `Nl`, altro `No`
16+
- Punteggiatura `P`:
17+
- connettore `Pc`, trattino `Pd`, apri virgolette `Pi`, chiudi virgolette `Pf`, apri `Ps`, chiudi `Pe`, altro `Po`
18+
- Mark `M` (accenti ecc.):
19+
- combinazione di spazi `Mc`, simboli di enclosing `Me`, caratteri non-spacing `Mn`
20+
- Simbolo `S`:
21+
- valuta `Sc`, modificatore `Sk`, matematico `Sm`, altro `So`
22+
- Separatore `Z`:
23+
- linea `Zl`, paragrafo `Zp`, spazio `Zs`
24+
- Altro `C`:
25+
- controllo `Cc`, formato `Cf`, non assegnato `Cn`, uso privato `Co`, surrogato `Cs`
2626

27-
```smart header="More information"
28-
Interested to see which characters belong to a property? There's a tool at <http://cldr.unicode.org/unicode-utilities/list-unicodeset> for that.
27+
```smart header="Maggiori informazioni"
28+
Ti interessa scoprire quali caratteri appartengono a una proprietà? C'è uno strumento in <http://cldr.unicode.org/unicode-utilities/list-unicodeset> che serve a questo.
2929
30-
You could also explore properties at [Character Property Index](http://unicode.org/cldr/utility/properties.jsp).
30+
Potresti anche esplorare le proprietà in [Character Property Index](http://unicode.org/cldr/utility/properties.jsp).
3131
32-
For the full Unicode Character Database in text format (along with all properties), see <https://www.unicode.org/Public/UCD/latest/ucd/>.
32+
Per il Database completo dei Caratteri Unicode in formato testuale (insieme a tutte le proprietà), vedi <https://www.unicode.org/Public/UCD/latest/ucd/>.
3333
```
3434

35-
There are also other derived categories, like:
36-
- `Alphabetic` (`Alpha`), includes Letters `L`, plus letter numbers `Nl` (e.g. roman numbers Ⅻ), plus some other symbols `Other_Alphabetic` (`OAltpa`).
37-
- `Hex_Digit` includes hexadecimal digits: `0-9`, `a-f`.
38-
- ...Unicode is a big beast, it includes a lot of properties.
35+
Ci sono anche altre categorie derivate, come:
36+
- `Alphabetic` (`Alpha`), include Lettere `L`, più numeri letterali `Nl` (es. i numeri romani Ⅻ), più qualche altro simbolo `Other_Alphabetic` (`OAltpa`).
37+
- `Hex_Digit` include i numeri esadecimali: `0-9`, `a-f`.
38+
- ...Unicode è un sistema complesso, include moltissime proprietà.
3939

40-
For instance, let's look for a 6-digit hex number:
40+
Per esempio, cerchiamo un numero esadecimale a 6 cifre:
4141

4242
```js run
43-
let reg = /\p{Hex_Digit}{6}/u; // flag 'u' is required
43+
let reg = /\p{Hex_Digit}{6}/u; // è richiesta la flag 'u'
4444

4545
alert("color: #123ABC".match(reg)); // 123ABC
4646
```
4747

48-
There are also properties with a value. For instance, Unicode "Script" (a writing system) can be Cyrillic, Greek, Arabic, Han (Chinese) etc, the [list is long]("https://en.wikipedia.org/wiki/Script_(Unicode)").
48+
Ci sono anche proprietà con un valore. Ad esempio, Unicode "Script" (un sistema di scrittura) può essere Cirillico, Greco, Arabo, Han (Cinese) ecc, la [lista è lunga]("https://en.wikipedia.org/wiki/Script_(Unicode)").
4949

50-
To search for characters in certain scripts ("alphabets"), we should supply `Script=<value>`, e.g. to search for cyrillic letters: `\p{sc=Cyrillic}`, for Chinese glyphs: `\p{sc=Han}`, etc:
50+
Per cercare caratteri in certi script ("alfabeti"), dovremmo fornire `Script=<value>`, ad esempio per cercare lettere in Cirillico: `\p{sc=Cyrillic}`, per glifi Cinesi: `\p{sc=Han}`, ecc:
5151

5252
```js run
53-
let regexp = /\p{sc=Han}+/gu; // get chinese words
53+
let regexp = /\p{sc=Han}+/gu; // ottieni parole cinesi
5454

5555
let str = `Hello Привет 你好 123_456`;
5656

5757
alert( str.match(regexp) ); // 你好
5858
```
5959

60-
## Building multi-language \w
60+
## Costruire un multi linguaggio \w
6161

62-
The pattern `pattern:\w` means "wordly characters", but doesn't work for languages that use non-Latin alphabets, such as Cyrillic and others. It's just a shorthand for `[a-zA-Z0-9_]`, so `pattern:\w+` won't find any Chinese words etc.
62+
Il pattern `pattern:\w` vuol dire "caratteri per formare parole", ma non funziona per lingue che usano alfabeti non Latini, come il Cirillico e altri. È solo un'abbreviazione per `[a-zA-Z0-9_]`, quindi `pattern:\w+` non troverà nessuna parola Cinese ecc.
6363

64-
Let's make a "universal" regexp, that looks for wordly characters in any language. That's easy to do using Unicode properties:
64+
Creiamo una regexp "universale", che cerca "caratteri letterari" in qualsiasi lingua. È semplice da fare utilizzando le proprietà di Unicode:
6565

6666
```js
6767
/[\p{Alphabetic}\p{Mark}\p{Decimal_Number}\p{Connector_Punctuation}\p{Join_Control}]/u
6868
```
6969

70-
Let's decipher. Just as `pattern:\w` is the same as `pattern:[a-zA-Z0-9_]`, we're making a set of our own, that includes:
70+
Decifriamolo. Proprio come `pattern:\w` è lo stesso di `pattern:[a-zA-Z0-9_]`, stiamo creando un nostro set personalizzato, che include:
7171

72-
- `Alphabetic` for letters,
73-
- `Mark` for accents, as in Unicode accents may be represented by separate code points,
74-
- `Decimal_Number` for numbers,
75-
- `Connector_Punctuation` for the `'_'` character and alike,
76-
- `Join_Control` -– two special code points with hex codes `200c` and `200d`, used in ligatures e.g. in arabic.
72+
- `Alphabetic` per le lettere,
73+
- `Mark` per accenti, dato che in Unicode gli accenti potrebbero essere rappresentati con codici separati,
74+
- `Decimal_Number` per i numeri,
75+
- `Connector_Punctuation` per il carattere `'_'` e simili,
76+
- `Join_Control` -– due codici speciali con codice esadecimale `200c` e `200d`, usati ad esempio in Arabo.
7777

78-
Or, if we replace long names with aliases (a list of aliases [here](https://www.unicode.org/Public/UCD/latest/ucd/PropertyValueAliases.txt)):
78+
O, se sostituiamo nomi lunghi con degli alias (una lista di alias [qui](https://www.unicode.org/Public/UCD/latest/ucd/PropertyValueAliases.txt)):
7979

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

0 commit comments

Comments
 (0)