|
1 | | -# Unicode: flag "u" and class \p{...} |
| 1 | +# Unicode: flag "u" e classe \p{...} |
2 | 2 |
|
3 | | -JavaScript uses [Unicode encoding](https://en.wikipedia.org/wiki/Unicode) for strings. Most characters are encoded with 2 bytes, but that allows to represent at most 65536 characters. |
| 3 | +O JavaScript usa a [codificação Unicode](https://pt.wikipedia.org/wiki/Unicode) para strings. A maioria dos caracteres são codificados com 2 bytes, mas isso só permite representar no máximo 65536 caracteres diferentes. |
4 | 4 |
|
5 | | -That range is not big enough to encode all possible characters, that's why some rare characters are encoded with 4 bytes, for instance like `𝒳` (mathematical X) or `😄` (a smile), some hieroglyphs and so on. |
| 5 | +Esse alcance não é grande o bastante para codificar todos os caracteres possíveis, por isso alguns caracteres são codificados com 4 bytes, como o `𝒳` (X matemático) ou o `😄` (emoji sorridente), alguns hieróglifos e assim por diante. |
6 | 6 |
|
7 | | -Here are the Unicode values of some characters: |
| 7 | +Aqui estão os valores no Unicode de alguns caracteres: |
8 | 8 |
|
9 | | -| Character | Unicode | Bytes count in Unicode | |
| 9 | +| Carácter | Unicode | Contagem de bytes no Unicode | |
10 | 10 | |------------|---------|--------| |
11 | 11 | | a | `0x0061` | 2 | |
12 | 12 | | ≈ | `0x2248` | 2 | |
13 | 13 | |𝒳| `0x1d4b3` | 4 | |
14 | 14 | |𝒴| `0x1d4b4` | 4 | |
15 | 15 | |😄| `0x1f604` | 4 | |
16 | 16 |
|
17 | | -So characters like `a` and `≈` occupy 2 bytes, while codes for `𝒳`, `𝒴` and `😄` are longer, they have 4 bytes. |
| 17 | +Note que caracteres como `a` e `≈` ocupam 2 bytes, enquanto os códigos para `𝒳`, `𝒴` e `😄` são maiores, e ocupam 4 bytes. |
18 | 18 |
|
19 | | -Long time ago, when JavaScript language was created, Unicode encoding was simpler: there were no 4-byte characters. So, some language features still handle them incorrectly. |
| 19 | +Há muito tempo atrás, quando o JavaScript foi criado, a codificação Unicode era mais simples: não haviam caracteres de 4 bytes. Então, algumas funcionalidades da linguagem ainda lidam com estes incorretamente. |
20 | 20 |
|
21 | | -For instance, `length` thinks that here are two characters: |
| 21 | +Por exemplo, o método `length` pensa que aqui há dois caracteres: |
22 | 22 |
|
23 | 23 | ```js run |
24 | 24 | alert('😄'.length); // 2 |
25 | 25 | alert('𝒳'.length); // 2 |
26 | 26 | ``` |
27 | 27 |
|
28 | | -...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", you can read about them in the article <info:string>). |
| 28 | +...Mas nós podemos ver que há apenas um, certo? O ponto é que o método `length` trata 4 bytes como dois caracteres de 2 bytes. Isso está errado, porque eles devem ser somente considerados juntos (os chamados "pares de substitutos", você pode ler mais sobre eles no artigo <info:string>). |
29 | 29 |
|
30 | | -By default, regular expressions also treat 4-byte "long characters" as a pair of 2-byte ones. And, as it happens with strings, that may lead to odd results. We'll see that a bit later, in the article <info:regexp-character-sets-and-ranges>. |
| 30 | +Por padrão, expressões regulares também tratam "caracteres compridos" de 4 bytes como um par de caracteres de 2 bytes. E, da mesma maneira que acontece com strings, isso pode levar a resultados estranhos. Veremos isso mais adiante, no artigo <info:regexp-character-sets-and-ranges>. |
31 | 31 |
|
32 | | -Unlike strings, regular expressions have flag `pattern:u` that fixes such problems. With such flag, a regexp handles 4-byte characters correctly. And also Unicode property search becomes available, we'll get to it next. |
| 32 | +Diferente de strings, expressões regulares têm a flag `pattern:u` que resolve tais problemas. com essa flag, uma regexp lida com caracteres de 4 bytes corretamente. Busca por propriedades do Unicode também se torna disponível, abordaremos o assunto a seguir. |
33 | 33 |
|
34 | | -## Unicode properties \p{...} |
| 34 | +## Propriedades Unicode \p{...} |
35 | 35 |
|
36 | | -Every character in Unicode has a lot of properties. They describe what "category" the character belongs to, contain miscellaneous information about it. |
| 36 | +Cada carácter no Unicode tem diversas propriedades. Elas descrevem a "categoria" a qual o carácter pertence, e contém informações miscelâneas sobre ele. |
37 | 37 |
|
38 | | -For instance, if a character has `Letter` property, it means that the character belongs to an alphabet (of any language). And `Number` property means that it's a digit: maybe Arabic or Chinese, and so on. |
| 38 | +Por exemplo, se um carácter possui a propriedade `Letter`, isso significa que o carácter pertence a um alfabeto (de qualquer língua). A propriedade `Number` indica que é um dígito: talvez Árabe ou Chinês, e assim por diante. |
39 | 39 |
|
40 | | -We can search for characters with a property, written as `pattern:\p{…}`. To use `pattern:\p{…}`, a regular expression must have flag `pattern:u`. |
| 40 | +Podemos buscar por caracteres baseado em suas propriedades, escrito como `pattern:\p{…}`. Para usar o `pattern:\p{…}`, a expressão regular deve possuir a flag `pattern:u`. |
41 | 41 |
|
42 | | -For instance, `\p{Letter}` denotes a letter in any language. We can also use `\p{L}`, as `L` is an alias of `Letter`. There are shorter aliases for almost every property. |
| 42 | +Por exemplo, `\p{Letter}` denota uma letra em qualquer língua. Também podemos usar `\p{L}`, já que `L` é um apelido (do Inglês: _alias_) de `Letter`. Existem apelidos curtos para quase todas as propriedades. |
43 | 43 |
|
44 | | -In the example below three kinds of letters will be found: English, Georgian and Korean. |
| 44 | +No exemplo abaixo três tipos de letras serão encontrados: Inglês, Georgiano e Coreano. |
45 | 45 |
|
46 | 46 | ```js run |
47 | 47 | let str = "A ბ ㄱ"; |
48 | 48 |
|
49 | 49 | alert( str.match(/\p{L}/gu) ); // A,ბ,ㄱ |
50 | | -alert( str.match(/\p{L}/g) ); // null (no matches, \p doesn't work without the flag "u") |
| 50 | +alert( str.match(/\p{L}/g) ); // null (nenhuma correspondência, \p não funciona sem a flag "u") |
51 | 51 | ``` |
52 | 52 |
|
53 | | -Here's the main character categories and their subcategories: |
54 | | - |
55 | | -- Letter `L`: |
56 | | - - lowercase `Ll` |
57 | | - - modifier `Lm`, |
58 | | - - titlecase `Lt`, |
59 | | - - uppercase `Lu`, |
60 | | - - other `Lo`. |
61 | | -- Number `N`: |
62 | | - - decimal digit `Nd`, |
63 | | - - letter number `Nl`, |
64 | | - - other `No`. |
65 | | -- Punctuation `P`: |
66 | | - - connector `Pc`, |
67 | | - - dash `Pd`, |
68 | | - - initial quote `Pi`, |
69 | | - - final quote `Pf`, |
70 | | - - open `Ps`, |
71 | | - - close `Pe`, |
72 | | - - other `Po`. |
73 | | -- Mark `M` (accents etc): |
74 | | - - spacing combining `Mc`, |
75 | | - - enclosing `Me`, |
76 | | - - non-spacing `Mn`. |
77 | | -- Symbol `S`: |
78 | | - - currency `Sc`, |
79 | | - - modifier `Sk`, |
80 | | - - math `Sm`, |
81 | | - - other `So`. |
82 | | -- Separator `Z`: |
83 | | - - line `Zl`, |
84 | | - - paragraph `Zp`, |
85 | | - - space `Zs`. |
86 | | -- Other `C`: |
87 | | - - control `Cc`, |
88 | | - - format `Cf`, |
89 | | - - not assigned `Cn`, |
90 | | - - private use `Co`, |
91 | | - - surrogate `Cs`. |
92 | | - |
93 | | - |
94 | | -So, e.g. if we need letters in lower case, we can write `pattern:\p{Ll}`, punctuation signs: `pattern:\p{P}` and so on. |
95 | | - |
96 | | -There are also other derived categories, like: |
97 | | -- `Alphabetic` (`Alpha`), includes Letters `L`, plus letter numbers `Nl` (e.g. Ⅻ - a character for the roman number 12), plus some other symbols `Other_Alphabetic` (`OAlpha`). |
98 | | -- `Hex_Digit` includes hexadecimal digits: `0-9`, `a-f`. |
99 | | -- ...And so on. |
100 | | - |
101 | | -Unicode supports many different properties, their full list would require a lot of space, so here are the references: |
102 | | - |
103 | | -- List all properties by a character: <https://unicode.org/cldr/utility/character.jsp>. |
104 | | -- List all characters by a property: <https://unicode.org/cldr/utility/list-unicodeset.jsp>. |
105 | | -- Short aliases for properties: <https://www.unicode.org/Public/UCD/latest/ucd/PropertyValueAliases.txt>. |
106 | | -- A full base of Unicode characters in text format, with all properties, is here: <https://www.unicode.org/Public/UCD/latest/ucd/>. |
| 53 | +Estas são as principais categorias de caracteres e suas sub-categorias: |
| 54 | + |
| 55 | +- Letra `L`: |
| 56 | + - minúscula `Ll` |
| 57 | + - modificadora `Lm`, |
| 58 | + - titular `Lt`, |
| 59 | + - maiúscula `Lu`, |
| 60 | + - outra `Lo`. |
| 61 | +- Número `N`: |
| 62 | + - dígito decimal `Nd`, |
| 63 | + - letras numéricas `Nl`, |
| 64 | + - outro `No`. |
| 65 | +- Pontuação `P`: |
| 66 | + - conector `Pc`, |
| 67 | + - traço `Pd`, |
| 68 | + - abertura de citação `Pi`, |
| 69 | + - fechamento de citação `Pf`, |
| 70 | + - abertura `Ps`, |
| 71 | + - fechamento `Pe`, |
| 72 | + - outro `Po`. |
| 73 | +- Marcação `M` (diacríticos, etc.): |
| 74 | + - com espaço `Mc`, |
| 75 | + - envolvente `Me`, |
| 76 | + - sem espaço `Mn`. |
| 77 | +- Símbolo `S`: |
| 78 | + - moeda `Sc`, |
| 79 | + - modificador `Sk`, |
| 80 | + - matemático `Sm`, |
| 81 | + - outro `So`. |
| 82 | +- Separador `Z`: |
| 83 | + - linha `Zl`, |
| 84 | + - parágrafo `Zp`, |
| 85 | + - espaço `Zs`. |
| 86 | +- Outro `C`: |
| 87 | + - controle `Cc`, |
| 88 | + - formato `Cf`, |
| 89 | + - não atribuído `Cn`, |
| 90 | + - uso reservado `Co`, |
| 91 | + - substituto `Cs`. |
| 92 | + |
| 93 | + |
| 94 | +Então, se precisarmos de letras minúsculas por exemplo, podemos escrever `pattern:\p{Ll}`, símbolos de pontuação: `pattern:\p{P}` e assim por diante. |
| 95 | + |
| 96 | +Existem outras categorias derivadas, como: |
| 97 | +- `Alphabetic` (`Alpha`), inclui a categoria "Letters" `L`, e letras numéricas `Nl` (Exemplo: Ⅻ - Um carácter para o número romano 12), além de alguns outros símbolos `Other_Alphabetic` (`OAlpha`). |
| 98 | +- `Hex_Digit` inclui dígitos hexadecimais: `0-9`, `a-f`. |
| 99 | +- ...E assim por diante. |
| 100 | + |
| 101 | +O Unicode suporta muitas propriedades diferentes, e a lista completa precisaria de muito espaço, então aqui estão as referências: |
| 102 | + |
| 103 | +- Lista de todas as propriedades por carácter: <https://unicode.org/cldr/utility/character.jsp>. |
| 104 | +- Lista de todos os caracteres por propriedade: <https://unicode.org/cldr/utility/list-unicodeset.jsp>. |
| 105 | +- Apelidos curtos das propriedades: <https://www.unicode.org/Public/UCD/latest/ucd/PropertyValueAliases.txt>. |
| 106 | +- A base completa dos caracteres Unicode em formato textual, com todas as suas propriedades, está aqui: <https://www.unicode.org/Public/UCD/latest/ucd/>. |
107 | 107 |
|
108 | 108 | ### Example: hexadecimal numbers |
109 | 109 |
|
|
0 commit comments