You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Let's say we have a string like `+7(903)-123-45-67`and want to find all numbers in it. But unlike before, we are interested not in single digits, but full numbers: `7, 903, 123, 45, 67`.
3
+
Digamos que temos a string `+7(903)-123-45-67`em mãos e gostaríamos de encontrar todos os números dela. Entretanto, diferente de casos anteriores, não estamos interessados em dígitos soltos, mas sim nos números inteiros: `7, 903, 123, 45, 67`.
4
4
5
-
A number is a sequence of 1 or more digits`pattern:\d`. To mark how many we need, we can append a *quantifier*.
5
+
Um número é uma sequência de 1 ou mais dígitos`pattern:\d`. Para determinar quantos desses precisamos, usamos um *quantificador*.
6
6
7
-
## Quantity {n}
7
+
## Quantidade {n}
8
8
9
-
The simplest quantifier is a number in curly braces: `pattern:{n}`.
9
+
O quantificador mais simples é um número entre chaves: `pattern:{n}`.
10
10
11
-
A quantifier is appended to a character (or a character class, or a `[...]` set etc) and specifies how many we need.
11
+
Quantificadores são colocados após um caractere (ou uma classe de caracteres, ou um conjunto `[...]`, etc.) e especifica quantos do elemento anterior nós precisamos.
12
12
13
-
It has a few advanced forms, let's see examples:
13
+
Ele possui algumas formas avançadas, vejamos alguns exemplos:
14
14
15
-
The exact count: `pattern:{5}`
16
-
: `pattern:\d{5}`denotes exactly 5 digits, the same as`pattern:\d\d\d\d\d`.
O exemplo abaixo procura por um número de 5 dígitos:
19
19
20
20
```js run
21
-
alert( "I'm 12345 years old".match(/\d{5}/) ); // "12345"
21
+
alert( "Eu tenho 12345 anos de idade".match(/\d{5}/) ); // "12345"
22
22
```
23
23
24
-
We can add `\b` to exclude longer numbers: `pattern:\b\d{5}\b`.
24
+
Podemos usar o `\b` para não reconhecer números maiores: `pattern:\b\d{5}\b`.
25
25
26
-
The range: `pattern:{3,5}`, match 3-5 times
27
-
: To find numbers from 3 to 5 digits we can put the limits into curly braces: `pattern:\d{3,5}`
26
+
Um alcance: `pattern:{3,5}`, repetição de 3 a 5 vezes
27
+
: Para encontrar números de 3 a 5 dígitos, podemos usar os limites entre chaves e separados por uma vírgula: `pattern:\d{3,5}`
28
28
29
29
```js run
30
-
alert( "I'm not 12, but 1234 years old".match(/\d{3,5}/) ); // "1234"
30
+
alert( "Não tenho 12, mas sim 1234 anos de idade".match(/\d{3,5}/) ); // "1234"
31
31
```
32
32
33
-
We can omit the upper limit.
33
+
Também podemos omitir o limite máximo.
34
34
35
-
Then a regexp `pattern:\d{3,}` looks for sequences of digits of length `3` or more:
35
+
Dessa forma, a expressão `pattern:\d{3,}` reconhece qualquer número com no mínimo 3 dígitos:
36
36
37
37
```js run
38
-
alert( "I'm not 12, but 345678 years old".match(/\d{3,}/) ); // "345678"
38
+
alert( "Não tenho 12, mas sim 345678 anos de idade".match(/\d{3,}/) ); // "345678"
39
39
```
40
40
41
-
Let's return to the string `+7(903)-123-45-67`.
41
+
Voltaremos à string `+7(903)-123-45-67`.
42
42
43
-
A number is a sequence of one or more digits in a row. So the regexp is`pattern:\d{1,}`:
43
+
Um número é uma sequência contínua de um ou mais dígitos. Com base nisso, a expressão regular equivalente é`pattern:\d{1,}`:
44
44
45
45
```js run
46
46
let str ="+7(903)-123-45-67";
@@ -50,14 +50,14 @@ let numbers = str.match(/\d{1,}/g);
50
50
alert(numbers); // 7,903,123,45,67
51
51
```
52
52
53
-
## Shorthands
53
+
## Atalhos
54
54
55
-
There are shorthands for most used quantifiers:
55
+
Existem atalhos para os quantificadores mais usados:
56
56
57
57
`pattern:+`
58
-
: Means "one or more", the same as`pattern:{1,}`.
58
+
: Representa "um ou mais da captura anterior", equivalente ao`pattern:{1,}`.
59
59
60
-
For instance, `pattern:\d+` looks for numbers:
60
+
O padrão `pattern:\d+`, por exemplo, encontra números:
61
61
62
62
```js run
63
63
let str = "+7(903)-123-45-67";
@@ -66,77 +66,78 @@ There are shorthands for most used quantifiers:
66
66
```
67
67
68
68
`pattern:?`
69
-
: Means "zero or one", the same as `pattern:{0,1}`. In other words, it makes the symbol optional.
69
+
: Representa "zero ou um da captura anterior", equivalente ao `pattern:{0,1}`; marca partes da expressão como opcionais.
70
70
71
-
For instance, the pattern `pattern:ou?r` looks for `match:o` followed by zero or one `match:u`, and then `match:r`.
71
+
O padrão `pattern:ou?r`, por exemplo, busca por `match:o` seguido de zero ou um `match:u`, seguido de um `match:r`.
72
72
73
-
So, `pattern:colou?r` finds both `match:color` and `match:colour`:
73
+
Dessa forma, `pattern:colou?r` reconhece ambos `match:color` e `match:colour`:
74
74
75
75
```js run
76
+
// Tradução: Devo escrever cor (em inglês americano) ou cor (em inglês britânico)?
76
77
let str = "Should I write color or colour?";
77
78
78
79
alert( str.match(/colou?r/g) ); // color, colour
79
80
```
80
81
81
82
`pattern:*`
82
-
: Means "zero or more", the same as `pattern:{0,}`. That is, the character may repeat any times or be absent.
83
+
: Representa "zero ou mais da captura anterior", equivalente ao `pattern:{0,}`; partes da expressão afetadas por esse quantificador podem se repetir indefinidamente ou não estarem presentes
83
84
84
-
For example, `pattern:\d0*` looks for a digit followed by any number of zeroes (may be many or none):
85
+
Por exemplo: O padrão `pattern:\d0*` procura por um dígito seguido de qualquer quantidade de zeros (nenhum ou quantos tiverem):
85
86
86
87
```js run
87
88
alert( "100 10 1".match(/\d0*/g) ); // 100, 10, 1
88
89
```
89
90
90
-
Compare it with `pattern:+` (one or more):
91
+
Comparando com o `pattern:+` (um ou mais):
91
92
92
93
```js run
93
94
alert( "100 10 1".match(/\d0+/g) ); // 100, 10
94
-
// 1 not matched, as 0+ requires at least one zero
95
+
// 1 não é reconhecido, já que 0+ requer ao menos uma ocorrência do 0
95
96
```
96
97
97
-
## More examples
98
+
## Outros exemplos
98
99
99
-
Quantifiers are used very often. They serve as the main "building block" of complex regular expressions, so let's see more examples.
100
+
Quantificadores são usados muito frequentemente. Eles servem como um dos principais componentes de expressões regulares complexas; vejamos mais alguns exemplos.
100
101
101
-
**Regexp for decimal fractions (a number with a floating point): `pattern:\d+\.\d+`**
102
+
**Regex para números com casas decimais: `pattern:\d+\.\d+`**
**Regexp "opening or closing HTML-tag without attributes":`pattern:/<\/?[a-z][a-z0-9]*>/i`**
127
+
**Regex de uma abertura ou fechamento de um elemento HTML sem atributos:`pattern:/<\/?[a-z][a-z0-9]*>/i`**
127
128
128
-
We added an optional slash `pattern:/?`near the beginning of the pattern. Had to escape it with a backslash, otherwise JavaScript would think it is the pattern end.
129
+
Adicionamos uma barra opcional `pattern:/?`próxima ao começo do padrão. Ela deve ser escapada com uma contrabarra, caso contrário, o JavaScript pode interpretá-lo como o fim da expressão.
```smart header="To make a regexp more precise, we often need make it more complex"
135
-
We can see one common rule in these examples: the more precise is the regular expression -- the longer and more complex it is.
135
+
```smart header="Para tornar uma expressão regular mais precisa, muitas vezes precisamos torná-la mais complexa"
136
+
Podemos ver uma característica em comum entre esses exemplos: Quanto mais precisa é a expressão regular, mais comprida e complexa ela se torna.
136
137
137
-
For instance, for HTML tags we could use a simpler regexp: `pattern:<\w+>`. But as HTML has stricter restrictions for a tag name, `pattern:<[a-z][a-z0-9]*>`is more reliable.
138
+
Para elementos HTML, por exemplo, podemos usar uma expressão mais simples: `pattern:<\w+>`. Mas por conta das restrições de possíveis nomes para um elemento HTML, o padrão `pattern:<[a-z][a-z0-9]*>`é mais confiável.
138
139
139
-
Can we use `pattern:<\w+>`or we need`pattern:<[a-z][a-z0-9]*>`?
140
+
Qual devemos usar então, o `pattern:<\w+>`ou o`pattern:<[a-z][a-z0-9]*>`?
140
141
141
-
In real life both variants are acceptable. Depends on how tolerant we can be to "extra" matches and whether it's difficult or not to remove them from the result by other means.
142
+
Na prática, ambas as variações são aceitáveis. Tudo depende de quantas correspondências "extras" podemos aceitar, e qual a dificuldade de removê-las do nosso resultado depois da captura usando outros meios.
0 commit comments