Skip to content

Commit b4ee5de

Browse files
docs: translate quantifiers +, *, ? and {n} article
Quantifiers +, *, ? and {n} by: @peruibeloko, @jonnathan-ls, and @nazarepiedady
2 parents eca3fe6 + f2dd836 commit b4ee5de

File tree

5 files changed

+71
-70
lines changed

5 files changed

+71
-70
lines changed
Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11

2-
Solution:
2+
Solução:
33

44
```js run
55
let regexp = /\.{3,}/g;
6-
alert( "Hello!... How goes?.....".match(regexp) ); // ..., .....
6+
alert( "Olá!... Como está?.....".match(regexp) ); // ..., .....
77
```
88

9-
Please note that the dot is a special character, so we have to escape it and insert as `\.`.
9+
Note que o ponto é um caractere especial (também conhecido como metacaractere), então devemos escapá-lo usando uma contrabarra: `\.`.

9-regular-expressions/09-regexp-quantifiers/1-find-text-manydots/task.md

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,13 @@ importance: 5
22

33
---
44

5-
# How to find an ellipsis "..." ?
5+
# Como encontrar reticências "..." ?
66

7-
Create a regexp to find ellipsis: 3 (or more?) dots in a row.
7+
Crie uma expressão regular que reconhece reticências: 3 (ou mais?) pontos consecutivos.
88

9-
Check it:
9+
Seu teste:
1010

1111
```js
12-
let regexp = /your regexp/g;
13-
alert( "Hello!... How goes?.....".match(regexp) ); // ..., .....
12+
let regexp = /sua expressão/g;
13+
alert( "Olá!... Como está?.....".match(regexp) ); // ..., .....
1414
```
Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
1-
We need to look for `#` followed by 6 hexadecimal characters.
1+
Precisamos buscar pela cerquilha `#` seguida por 6 caracteres hexadecimais.
22

3-
A hexadecimal character can be described as `pattern:[0-9a-fA-F]`. Or if we use the `pattern:i` flag, then just `pattern:[0-9a-f]`.
3+
Um caractere hexadecimal pode ser descrito como `pattern:[0-9a-fA-F]`, ou usando a opção `pattern:i`, apenas `pattern:[0-9a-f]`.
44

5-
Then we can look for 6 of them using the quantifier `pattern:{6}`.
5+
Podemos então buscar por 6 deles usando o quantificador `pattern:{6}`.
66

7-
As a result, we have the regexp: `pattern:/#[a-f0-9]{6}/gi`.
7+
Nosso resultado final é a expressão: `pattern:/#[a-f0-9]{6}/gi`.
88

99
```js run
1010
let regexp = /#[a-f0-9]{6}/gi;
@@ -14,18 +14,18 @@ let str = "color:#121212; background-color:#AA00ef bad-colors:f#fddee #fd2"
1414
alert( str.match(regexp) ); // #121212,#AA00ef
1515
```
1616

17-
The problem is that it finds the color in longer sequences:
17+
Mas temos um problema, essa expressão captura cores em sequências maiores:
1818

1919
```js run
2020
alert( "#12345678".match( /#[a-f0-9]{6}/gi ) ) // #123456
2121
```
2222

23-
To fix that, we can add `pattern:\b` to the end:
23+
Para consertar isso, adicionamos o `pattern:\b` ao final:
2424

2525
```js run
26-
// color
26+
// cor válida
2727
alert( "#123456".match( /#[a-f0-9]{6}\b/gi ) ); // #123456
2828

29-
// not a color
29+
// cor inválida
3030
alert( "#12345678".match( /#[a-f0-9]{6}\b/gi ) ); // null
3131
```
Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,15 @@
1-
# Regexp for HTML colors
1+
# Regex para cores hexadecimais
22

3-
Create a regexp to search HTML-colors written as `#ABCDEF`: first `#` and then 6 hexadecimal characters.
3+
Crie uma expressão regular que reconhece cores escritas no formato `#ABCDEF`: Primeiro um `#`, seguido de 6 caracteres hexadecimais
44

5-
An example of use:
5+
Um caso de uso para a expressão:
66

77
```js
8-
let regexp = /...your regexp.../
8+
let regexp = /...sua expressão.../
99

1010
let str = "color:#121212; background-color:#AA00ef bad-colors:f#fddee #fd2 #12345678";
1111

1212
alert( str.match(regexp) ) // #121212,#AA00ef
1313
```
1414

15-
P.S. In this task we do not need other color formats like `#123` or `rgb(1,2,3)` etc.
15+
P.S. Nesse exercício nós não precisamos de outros formatos de cor, como o `#123` ou `rgb(1,2,3)`, etc.
Lines changed: 50 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -1,46 +1,46 @@
1-
# Quantifiers +, *, ? and {n}
1+
# Quantificadores +, *, ? e {n}
22

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

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

7-
## Quantity {n}
7+
## Quantidade {n}
88

9-
The simplest quantifier is a number in curly braces: `pattern:{n}`.
9+
O quantificador mais simples é um número entre chaves: `pattern:{n}`.
1010

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

13-
It has a few advanced forms, let's see examples:
13+
Ele possui algumas formas avançadas, vejamos alguns exemplos:
1414

15-
The exact count: `pattern:{5}`
16-
: `pattern:\d{5}` denotes exactly 5 digits, the same as `pattern:\d\d\d\d\d`.
15+
Quantidade exata: `pattern:{5}`
16+
: `pattern:\d{5}` representa exatamente 5 dígitos, idêntico a `pattern:\d\d\d\d\d`.
1717

18-
The example below looks for a 5-digit number:
18+
O exemplo abaixo procura por um número de 5 dígitos:
1919

2020
```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"
2222
```
2323

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

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}`
2828

2929
```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"
3131
```
3232

33-
We can omit the upper limit.
33+
Também podemos omitir o limite máximo.
3434

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

3737
```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"
3939
```
4040

41-
Let's return to the string `+7(903)-123-45-67`.
41+
Voltaremos à string `+7(903)-123-45-67`.
4242

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,}`:
4444

4545
```js run
4646
let str = "+7(903)-123-45-67";
@@ -50,14 +50,14 @@ let numbers = str.match(/\d{1,}/g);
5050
alert(numbers); // 7,903,123,45,67
5151
```
5252

53-
## Shorthands
53+
## Atalhos
5454

55-
There are shorthands for most used quantifiers:
55+
Existem atalhos para os quantificadores mais usados:
5656

5757
`pattern:+`
58-
: Means "one or more", the same as `pattern:{1,}`.
58+
: Representa "um ou mais da captura anterior", equivalente ao `pattern:{1,}`.
5959

60-
For instance, `pattern:\d+` looks for numbers:
60+
O padrão `pattern:\d+`, por exemplo, encontra números:
6161

6262
```js run
6363
let str = "+7(903)-123-45-67";
@@ -66,77 +66,78 @@ There are shorthands for most used quantifiers:
6666
```
6767

6868
`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.
7070

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

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`:
7474

7575
```js run
76+
// Tradução: Devo escrever cor (em inglês americano) ou cor (em inglês britânico)?
7677
let str = "Should I write color or colour?";
7778

7879
alert( str.match(/colou?r/g) ); // color, colour
7980
```
8081

8182
`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
8384

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):
8586

8687
```js run
8788
alert( "100 10 1".match(/\d0*/g) ); // 100, 10, 1
8889
```
8990

90-
Compare it with `pattern:+` (one or more):
91+
Comparando com o `pattern:+` (um ou mais):
9192

9293
```js run
9394
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
9596
```
9697

97-
## More examples
98+
## Outros exemplos
9899

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

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+`**
102103

103-
In action:
104+
Em ação:
104105
```js run
105106
alert( "0 1 12.345 7890".match(/\d+\.\d+/g) ); // 12.345
106107
```
107108

108-
**Regexp for an "opening HTML-tag without attributes", such as `<span>` or `<p>`.**
109+
**Regex de uma abertura de elemento HTML sem atributos, como um `<span>` ou um `<p>`.**
109110

110-
1. The simplest one: `pattern:/<[a-z]+>/i`
111+
1. O mais simples: `pattern:/<[a-z]+>/i`
111112

112113
```js run
113114
alert( "<body> ... </body>".match(/<[a-z]+>/gi) ); // <body>
114115
```
115116

116-
The regexp looks for character `pattern:'<'` followed by one or more Latin letters, and then `pattern:'>'`.
117+
A expressão busca pelo caractere `pattern:'<'` seguido de uma ou mais letras do alfabeto latino, seguido de um caractere `pattern:'>'`.
117118

118-
2. Improved: `pattern:/<[a-z][a-z0-9]*>/i`
119+
2. Melhorado: `pattern:/<[a-z][a-z0-9]*>/i`
119120

120-
According to the standard, HTML tag name may have a digit at any position except the first one, like `<h1>`.
121+
De acordo com a norma, um elemento HTML pode ter um dígito em qualquer posição exceto a primeira, como no `<h1>`.
121122

122123
```js run
123-
alert( "<h1>Hi!</h1>".match(/<[a-z][a-z0-9]*>/gi) ); // <h1>
124+
alert( "<h1>Oi!</h1>".match(/<[a-z][a-z0-9]*>/gi) ); // <h1>
124125
```
125126

126-
**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`**
127128

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

130131
```js run
131-
alert( "<h1>Hi!</h1>".match(/<\/?[a-z][a-z0-9]*>/gi) ); // <h1>, </h1>
132+
alert( "<h1>Oi!</h1>".match(/<\/?[a-z][a-z0-9]*>/gi) ); // <h1>, </h1>
132133
```
133134

134-
```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.
136137
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.
138139
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]*>`?
140141
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.
142143
```

0 commit comments

Comments
 (0)