Skip to content

Commit de254ee

Browse files
committed
Merge branch 'master' of github.com:danilolmc/pt.javascript.info into update-reference-type
2 parents b207bc5 + 1067461 commit de254ee

File tree

4 files changed

+130
-130
lines changed

4 files changed

+130
-130
lines changed
Lines changed: 104 additions & 104 deletions
Original file line numberDiff line numberDiff line change
@@ -1,161 +1,161 @@
1-
# Unicode: flag "u" and class \p{...}
1+
# Unicode: flag "u" e classe \p{...}
22

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

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

7-
Here are the Unicode values of some characters:
7+
Aqui estão os códigos Unicode de alguns caracteres:
88

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 |
1616

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

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

21-
For instance, `length` thinks that here are two characters:
21+
Por exemplo, o método `length` pensa que aqui há dois caracteres:
2222

2323
```js run
24-
alert('😄'.length); // 2
25-
alert('𝒳'.length); // 2
24+
alert("😄".length); // 2
25+
alert("𝒳".length); // 2
2626
```
2727

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

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

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

34-
## Unicode properties \p{...}
34+
## Propriedades Unicode \p{...}
3535

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

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

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

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

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

4646
```js run
4747
let str = "A ბ ㄱ";
4848

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")
5151
```
5252

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}`:
113113

114114
```js run
115115
let regexp = /x\p{Hex_Digit}\p{Hex_Digit}/u;
116116

117117
alert("number: xAF".match(regexp)); // xAF
118118
```
119119

120-
### Example: Chinese hieroglyphs
120+
### Exemplo: Sinogramas Chineses
121121

122-
Let's look for Chinese hieroglyphs.
122+
Vamos procurar por sinogramas chineses.
123123

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

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

128128
```js run
129-
let regexp = /\p{sc=Han}/gu; // returns Chinese hieroglyphs
129+
let regexp = /\p{sc=Han}/gu; // retorna sinogramas chineses
130130

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

133-
alert( str.match(regexp) ); // 你,好
133+
alert(str.match(regexp)); // 你,好
134134
```
135135

136-
### Example: currency
136+
### Exemplo: Moeda
137137

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}`.
139139

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":
141141

142142
```js run
143143
let regexp = /\p{Sc}\d/gu;
144144

145145
let str = `Prices: $2, €1, ¥9`;
146146

147-
alert( str.match(regexp) ); // $2,€1,¥9
147+
alert(str.match(regexp)); // $2,€1,¥9
148148
```
149149

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

152-
## Summary
152+
## Sumário
153153

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

156-
That means two things:
156+
Isso resulta em duas coisas:
157157

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{…}`.
160160

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.
Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
An empty string is the only match: it starts and immediately finishes.
1+
Uma string vazia é a única correspondência: Ela começa e imediatamente termina.
22

3-
The task once again demonstrates that anchors are not characters, but tests.
3+
Esta tarefa demostra novamente que âncoras não são caracteres, mas sim testes.
44

5-
The string is empty `""`. The engine first matches the `pattern:^` (input start), yes it's there, and then immediately the end `pattern:$`, it's here too. So there's a match.
5+
A string está vazia `""`. O interpretador primeiro encontra o padrão de início da entrada `pattern:^` (que sim, está lá), e então imediatamente o fim da entrada `pattern:$` (que também está). Temos uma correspondência.
Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
1-
# Regexp ^$
1+
# Expressão Regular ^$
22

3-
Which string matches the pattern `pattern:^$`?
3+
Qual string corresponde ao padrão `pattern:^$`?
Lines changed: 21 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,34 @@
1-
# Anchors: string start ^ and end $
1+
# Âncoras: início ^ e fim $ de string
22

3-
The caret `pattern:^` and dollar `pattern:$` characters have special meaning in a regexp. They are called "anchors".
3+
Os caracteres acento circunflexo `pattern:^` e cifrão `pattern:$` possuem um significado especial em expressões regulares. Eles são chamados de "âncoras".
44

5-
The caret `pattern:^` matches at the beginning of the text, and the dollar `pattern:$` -- at the end.
5+
O acento circunflexo `pattern:^` corresponde ao início da string, e o cifrão `pattern:$` ao final.
66

7-
For instance, let's test if the text starts with `Mary`:
7+
Neste exemplo, vamos testar se o texto começa com `Maria`:
88

99
```js run
10-
let str1 = "Mary had a little lamb";
11-
alert( /^Mary/.test(str1) ); // true
10+
let str1 = "Maria tinha um cordeirinho";
11+
alert( /^Maria/.test(str1) ); // true
1212
```
1313

14-
The pattern `pattern:^Mary` means: "string start and then Mary".
14+
O padrão `pattern:^Maria` quer dizer: "início da string, e então Maria"
1515

16-
Similar to this, we can test if the string ends with `snow` using `pattern:snow$`:
16+
Da mesma maneira, podemos testar se a string termina com `neve` usando `pattern:neve$`:
1717

1818
```js run
19-
let str1 = "its fleece was white as snow";
20-
alert( /snow$/.test(str1) ); // true
19+
let str1 = "Seu velo era branco como a neve";
20+
alert( /neve$/.test(str1) ); // true
2121
```
2222

23-
In these particular cases we could use string methods `startsWith/endsWith` instead. Regular expressions should be used for more complex tests.
23+
Nesses casos em particular, poderíamos usar os métodos do objeto string `startsWith/endsWith` em seu lugar. Expressões regulares devem ser usadas para testes mais complexos.
2424

25-
## Testing for a full match
25+
## Correspondendo com uma string inteira
2626

27-
Both anchors together `pattern:^...$` are often used to test whether or not a string fully matches the pattern. For instance, to check if the user input is in the right format.
27+
Frequentemente, ambas as âncoras `pattern:^...$` são usadas juntas para verificar se uma string inteira corresponde ao padrão. Para confirmar, por exemplo, se a entrada do usuário está no formato correto.
2828

29-
Let's check whether or not a string is a time in `12:34` format. That is: two digits, then a colon, and then another two digits.
29+
Vamos verificar se uma string é um horário no formato `12:34`. Isto é: dois dígitos, seguido de dois pontos (':'), e então mais dois dígitos.
3030

31-
In regular expressions language that's `pattern:\d\d:\d\d`:
31+
Em expressões regulares, isso fica `pattern:\d\d:\d\d`:
3232

3333
```js run
3434
let goodInput = "12:34";
@@ -39,14 +39,14 @@ alert( regexp.test(goodInput) ); // true
3939
alert( regexp.test(badInput) ); // false
4040
```
4141

42-
Here the match for `pattern:\d\d:\d\d` must start exactly after the beginning of the text `pattern:^`, and the end `pattern:$` must immediately follow.
42+
Nesse exemplo, a correspondência com o padrão `pattern:\d\d:\d\d` deve iniciar exatamente após o início da string `pattern:^`, e ser seguido imediatamente pelo fim da string `pattern:$`.
4343

44-
The whole string must be exactly in this format. If there's any deviation or an extra character, the result is `false`.
44+
A string inteira deve obedecer exatamente a esse formato. Se houver qualquer desvio ou caractere adicional, o resultado será `false`.
4545

46-
Anchors behave differently if flag `pattern:m` is present. We'll see that in the next article.
46+
Âncoras tem um comportamento diferente caso a flag `pattern:m` esteja presente. Veremos isso no próximo artigo.
4747

48-
```smart header="Anchors have \"zero width\""
49-
Anchors `pattern:^` and `pattern:$` are tests. They have zero width.
48+
```smart header="Âncoras tem \"largura zero\""
49+
As âncoras `pattern:^` e `pattern:$` são verificações. Elas não possuem largura.
5050
51-
In other words, they do not match a character, but rather force the regexp engine to check the condition (text start/end).
51+
Em outras palavras, elas não correspondem com um caractere, mas sim com uma posição, obrigando o interpretador regex a verificar a condição de início ou fim da string.
5252
```

0 commit comments

Comments
 (0)