|
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 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 ideogramas e assim por diante. |
6 | 6 |
|
7 |
| -Here are the Unicode values of some characters: |
| 7 | +Aqui estão os códigos Unicode de alguns caracteres: |
8 | 8 |
|
9 |
| -| Character | Unicode | Bytes count in Unicode | |
10 |
| -|------------|---------|--------| |
11 |
| -| a | `0x0061` | 2 | |
12 |
| -| ≈ | `0x2248` | 2 | |
13 |
| -|𝒳| `0x1d4b3` | 4 | |
14 |
| -|𝒴| `0x1d4b4` | 4 | |
15 |
| -|😄| `0x1f604` | 4 | |
| 9 | +| Carácter | Unicode | Tamanho em bytes do caractere em Unicode | |
| 10 | +| -------- | --------- | ---------------------------------------- | |
| 11 | +| a | `0x0061` | 2 | |
| 12 | +| ≈ | `0x2248` | 2 | |
| 13 | +| 𝒳 | `0x1d4b3` | 4 | |
| 14 | +| 𝒴 | `0x1d4b4` | 4 | |
| 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 |
| -alert('😄'.length); // 2 |
25 |
| -alert('𝒳'.length); // 2 |
| 24 | +alert("😄".length); // 2 |
| 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 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 caractere no Unicode tem diversas propriedades. Elas descrevem a "categoria" a qual o caractere 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 caractere possui a propriedade `Letter`, isso significa que o caractere 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 |
| -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") |
| 49 | +alert(str.match(/\p{L}/gu)); // A,ბ,ㄱ |
| 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/>. |
107 |
| - |
108 |
| -### Example: hexadecimal numbers |
109 |
| - |
110 |
| -For instance, let's look for hexadecimal numbers, written as `xFF`, where `F` is a hex digit (0..9 or A..F). |
111 |
| - |
112 |
| -A hex digit can be denoted as `pattern:\p{Hex_Digit}`: |
| 53 | +Estas são as principais categorias de caracteres e suas sub-categorias: |
| 54 | + |
| 55 | +- Letra (Letter) `L`: |
| 56 | + - minúscula `Ll` |
| 57 | + - modificadora `Lm`, |
| 58 | + - titular `Lt`, |
| 59 | + - maiúscula `Lu`, |
| 60 | + - outra `Lo`. |
| 61 | +- Número (Number) `N`: |
| 62 | + - dígito decimal `Nd`, |
| 63 | + - letras numéricas `Nl`, |
| 64 | + - outro `No`. |
| 65 | +- Pontuação (Punctuation) `P`: |
| 66 | + - conector `Pc`, |
| 67 | + - traço `Pd`, |
| 68 | + - aspas esquerdas `Pi`, |
| 69 | + - aspas direitas `Pf`, |
| 70 | + - abertura `Ps`, |
| 71 | + - fechamento `Pe`, |
| 72 | + - outro `Po`. |
| 73 | +- Marcações Diacríticas (Mark) `M`: |
| 74 | + - com espaço `Mc`, |
| 75 | + - envolvente `Me`, |
| 76 | + - sem espaço `Mn`. |
| 77 | +- Símbolos (Symbol) `S`: |
| 78 | + - moeda `Sc`, |
| 79 | + - modificador `Sk`, |
| 80 | + - matemático `Sm`, |
| 81 | + - outro `So`. |
| 82 | +- Separadores (Separator) `Z`: |
| 83 | + - linha `Zl`, |
| 84 | + - parágrafo `Zp`, |
| 85 | + - espaço `Zs`. |
| 86 | +- Outros (Other) `C`: |
| 87 | + - controle `Cc`, |
| 88 | + - formato `Cf`, |
| 89 | + - não atribuído `Cn`, |
| 90 | + - uso reservado `Co`, |
| 91 | + - substituto `Cs`. |
| 92 | + |
| 93 | +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. |
| 94 | + |
| 95 | +Existem outras categorias derivadas, como: |
| 96 | + |
| 97 | +- `Alphabetic` (`Alpha`), inclui a categoria "Letters" `L`, e letras numéricas `Nl` (Exemplo: Ⅻ - Um caractere 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 caractere: <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 | + |
| 108 | +### Exemplo: Números hexadecimais |
| 109 | + |
| 110 | +Para este exemplo, vamos procurar por números hexadecimais, escritos como `xFF`, onde `F` é um dígito hexadecimal (0..9 ou A..F). |
| 111 | + |
| 112 | +Um dígito hexadecimal pode ser indicado por `pattern:\p{Hex_Digit}`: |
113 | 113 |
|
114 | 114 | ```js run
|
115 | 115 | let regexp = /x\p{Hex_Digit}\p{Hex_Digit}/u;
|
116 | 116 |
|
117 | 117 | alert("number: xAF".match(regexp)); // xAF
|
118 | 118 | ```
|
119 | 119 |
|
120 |
| -### Example: Chinese hieroglyphs |
| 120 | +### Exemplo: Sinogramas Chineses |
121 | 121 |
|
122 |
| -Let's look for Chinese hieroglyphs. |
| 122 | +Vamos procurar por sinogramas chineses. |
123 | 123 |
|
124 |
| -There's a Unicode property `Script` (a writing system), that may have a value: `Cyrillic`, `Greek`, `Arabic`, `Han` (Chinese) and so on, [here's the full list](https://en.wikipedia.org/wiki/Script_(Unicode)). |
| 124 | +Há uma propriedade Unicode chamada `Script` (sistema de escrita), que pode receber diferentes valores: `Cyrillic` (Cirílico: Russo, Ucraniano, Sérvio), `Greek` (Grego), `Arabic` (Árabe), `Han` (Chinês) e assim por diante, [a lista completa pode ser encontrada aqui](<https://en.wikipedia.org/wiki/Script_(Unicode)>). |
125 | 125 |
|
126 |
| -To look for characters in a given writing system we should use `pattern:Script=<value>`, e.g. for Cyrillic letters: `pattern:\p{sc=Cyrillic}`, for Chinese hieroglyphs: `pattern:\p{sc=Han}`, and so on: |
| 126 | +Para procurar por caracteres de um sistema de escrita específico nós devemos usar o `pattern:Script=<value>`. Para buscar letras cirílicas, por exemplo: `pattern:\p{sc=Cyrillic}`, para sinogramas chineses: `pattern:\p{sc=Han}`, e assim por diante: |
127 | 127 |
|
128 | 128 | ```js run
|
129 |
| -let regexp = /\p{sc=Han}/gu; // returns Chinese hieroglyphs |
| 129 | +let regexp = /\p{sc=Han}/gu; // retorna sinogramas chineses |
130 | 130 |
|
131 | 131 | let str = `Hello Привет 你好 123_456`;
|
132 | 132 |
|
133 |
| -alert( str.match(regexp) ); // 你,好 |
| 133 | +alert(str.match(regexp)); // 你,好 |
134 | 134 | ```
|
135 | 135 |
|
136 |
| -### Example: currency |
| 136 | +### Exemplo: Moeda |
137 | 137 |
|
138 |
| -Characters that denote a currency, such as `$`, `€`, `¥`, have Unicode property `pattern:\p{Currency_Symbol}`, the short alias: `pattern:\p{Sc}`. |
| 138 | +Caracteres que representam uma moeda, como `$`, `€`, `¥`, possuem a propriedade Unicode `pattern:\p{Currency_Symbol}`, de apelido: `pattern:\p{Sc}`. |
139 | 139 |
|
140 |
| -Let's use it to look for prices in the format "currency, followed by a digit": |
| 140 | +Vamos usá-la para procurar por preços no formato "símbolo de moeda, seguido de um dígito": |
141 | 141 |
|
142 | 142 | ```js run
|
143 | 143 | let regexp = /\p{Sc}\d/gu;
|
144 | 144 |
|
145 | 145 | let str = `Prices: $2, €1, ¥9`;
|
146 | 146 |
|
147 |
| -alert( str.match(regexp) ); // $2,€1,¥9 |
| 147 | +alert(str.match(regexp)); // $2,€1,¥9 |
148 | 148 | ```
|
149 | 149 |
|
150 |
| -Later, in the article <info:regexp-quantifiers> we'll see how to look for numbers that contain many digits. |
| 150 | +Mais adiante, no artigo <info:regexp-quantifiers> veremos como procurar por números que contém vários dígitos. |
151 | 151 |
|
152 |
| -## Summary |
| 152 | +## Sumário |
153 | 153 |
|
154 |
| -Flag `pattern:u` enables the support of Unicode in regular expressions. |
| 154 | +A flag `pattern:u` ativa o suporte ao Unicode em expressões regulares. |
155 | 155 |
|
156 |
| -That means two things: |
| 156 | +Isso resulta em duas coisas: |
157 | 157 |
|
158 |
| -1. Characters of 4 bytes are handled correctly: as a single character, not two 2-byte characters. |
159 |
| -2. Unicode properties can be used in the search: `\p{…}`. |
| 158 | +1. Caracteres de 4 bytes são reconhecidos corretamente: como um único caractere, não dois caracteres de 2 bytes. |
| 159 | +2. Propriedades Unicode podem ser usadas na busca, usando `\p{…}`. |
160 | 160 |
|
161 |
| -With Unicode properties we can look for words in given languages, special characters (quotes, currencies) and so on. |
| 161 | +Com as propriedades Unicode podemos buscar por palavras em línguas específicas, caracteres especiais (aspas, símbolos de moeda) e assim por diante. |
0 commit comments