Skip to content

Commit 0218fe7

Browse files
docs: translate the article patterns and flags
article translated: patterns and flags by: @jonnathan-ls, @odsantos, @nazarepiedady, @peruibeloko.
2 parents 7c6f74b + 91686e7 commit 0218fe7

File tree

1 file changed

+81
-81
lines changed
  • 9-regular-expressions/01-regexp-introduction

1 file changed

+81
-81
lines changed
+81-81
Original file line numberDiff line numberDiff line change
@@ -1,177 +1,177 @@
1-
# Patterns and flags
1+
# Padrões e flags
22

3-
Regular expressions are patterns that provide a powerful way to search and replace in text.
3+
Expressões regulares são padrões que fornecem uma maneira poderosa de pesquisar e substituir no texto.
44

5-
In JavaScript, they are available via the [RegExp](mdn:js/RegExp) object, as well as being integrated in methods of strings.
5+
Em JavaScript, elas estão disponíveis através do objeto [RegExp](mdn:js/RegExp), além de estarem integradas em métodos de strings.
66

7-
## Regular Expressions
7+
## Expressões regulares
88

9-
A regular expression (also "regexp", or just "reg") consists of a *pattern* and optional *flags*.
9+
Uma expressão regular (também "regexp" ou apenas "reg") consiste em um *padrão* e *flags* opcionais.
1010

11-
There are two syntaxes that can be used to create a regular expression object.
11+
Existem duas sintaxes que podem ser usadas para criar um objeto de expressão regular.
1212

13-
The "long" syntax:
13+
A sintaxe "longa":
1414

1515
```js
16-
regexp = new RegExp("pattern", "flags");
16+
regexp = new RegExp("padrão", "flags");
1717
```
1818

19-
And the "short" one, using slashes `"/"`:
19+
E a "curta", usando barras `"/"`:
2020

2121
```js
22-
regexp = /pattern/; // no flags
23-
regexp = /pattern/gmi; // with flags g,m and i (to be covered soon)
22+
regexp = /padrão/; // sem flags
23+
regexp = /padrão/gmi; // com flags `g`, `m` e `i` (a ser abordado em breve)
2424
```
2525

26-
Slashes `pattern:/.../` tell JavaScript that we are creating a regular expression. They play the same role as quotes for strings.
26+
Barras `pattern:/.../` informam ao JavaScript que estamos criando uma expressão regular. Eles desempenham o mesmo papel que aspas para strings.
2727

28-
In both cases `regexp` becomes an instance of the built-in `RegExp` class.
28+
Em ambos os casos, a `regexp` se torna numa instância da classe interna `RegExp`.
2929

30-
The main difference between these two syntaxes is that pattern using slashes `/.../` does not allow for expressions to be inserted (like string template literals with `${...}`). They are fully static.
30+
A principal diferença entre essas duas sintaxes é que o padrão usando barras `/.../` não permite a inserção de expressões (como modelos de string literais com `${...}`). Eles são totalmente estáticos.
3131

32-
Slashes are used when we know the regular expression at the code writing time -- and that's the most common situation. While `new RegExp` is more often used when we need to create a regexp "on the fly" from a dynamically generated string. For instance:
32+
As barras são usadas quando conhecemos a expressão regular no momento da escrita do código - e essa é a situação mais comum. Enquanto `new RegExp` é mais frequentemente usada quando precisamos criar uma regexp "de improviso" a partir de uma string gerada dinamicamente. Por exemplo:
3333

3434
```js
35-
let tag = prompt("What tag do you want to find?", "h2");
35+
let tag = prompt("Qual tag você deseja encontrar?", "h2");
3636

37-
let regexp = new RegExp(`<${tag}>`); // same as /<h2>/ if answered "h2" in the prompt above
37+
let regexp = new RegExp(`<${tag}>`); // igual a /<h2>/ se respondeu "h2" no prompt acima
3838
```
3939

4040
## Flags
4141

42-
Regular expressions may have flags that affect the search.
42+
Expressões regulares podem ter flags que afetam a pesquisa.
4343

44-
There are only 6 of them in JavaScript:
44+
Existem apenas 6 delas em JavaScript:
4545

4646
`pattern:i`
47-
: With this flag the search is case-insensitive: no difference between `A` and `a` (see the example below).
47+
: Com essa flag, a pesquisa não diferencia maiúsculas de minúsculas: não há diferença entre `A` e `a` (veja o exemplo abaixo).
4848

4949
`pattern:g`
50-
: With this flag the search looks for all matches, without it -- only the first match is returned.
50+
: Com essa flag, a pesquisa procura todas as correspondências, sem ela - somente a primeira correspondência é retornada.
5151

5252
`pattern:m`
53-
: Multiline mode (covered in the chapter <info:regexp-multiline-mode>).
53+
: Modo multilinha (abordado no capítulo <info:regexp-multiline-mode>).
5454

5555
`pattern:s`
56-
: Enables "dotall" mode, that allows a dot `pattern:.` to match newline character `\n` (covered in the chapter <info:regexp-character-classes>).
56+
: Ativa o modo "dotall", que permite que um ponto `pattern:.` corresponda ao caractere de nova linha `\n` (abordado no capítulo <info:regexp-character-classes>).
5757

5858
`pattern:u`
59-
: Enables full Unicode support. The flag enables correct processing of surrogate pairs. More about that in the chapter <info:regexp-unicode>.
59+
: Ativa o suporte completo de Unicode. A flag permite o processamento correto de pares substitutos. Mais sobre isso no capítulo <info:regexp-unicode>.
6060

6161
`pattern:y`
62-
: "Sticky" mode: searching at the exact position in the text (covered in the chapter <info:regexp-sticky>)
62+
: Modo "fixo": pesquisando na posição exata no texto (abordado no capítulo <info:regexp-sticky>)
6363

64-
```smart header="Colors"
65-
From here on the color scheme is:
64+
```smart header="Cores"
65+
A partir daqui, o esquema de cores é:
6666
67-
- regexp -- `pattern:red`
68-
- string (where we search) -- `subject:blue`
69-
- result -- `match:green`
67+
- regexp -- `pattern:vermelho`
68+
- string (onde pesquisamos) -- `subject:azul`
69+
- result -- `match:verde`
7070
```
7171

72-
## Searching: str.match
72+
## Pesquisando: str.match
7373

74-
As mentioned previously, regular expressions are integrated with string methods.
74+
Como mencionado anteriormente, expressões regulares são integradas a métodos de string.
7575

76-
The method `str.match(regexp)` finds all matches of `regexp` in the string `str`.
76+
O método `str.match(regexp)` encontra todas as correspondências de `regexp` na string `str`.
7777

78-
It has 3 working modes:
78+
Possui 3 modos de trabalho:
7979

80-
1. If the regular expression has flag `pattern:g`, it returns an array of all matches:
80+
1. Se a expressão regular tiver flag `pattern:g`, ela retornará uma matriz de todas as correspondências:
8181
```js run
82-
let str = "We will, we will rock you";
82+
let str = "Nós vamos, nós vamos sacudir você";
8383

84-
alert( str.match(/we/gi) ); // We,we (an array of 2 substrings that match)
84+
alert( str.match(/nós/gi) ); // Nós, nós (uma matriz de 2 substrings que correspondem)
8585
```
86-
Please note that both `match:We` and `match:we` are found, because flag `pattern:i` makes the regular expression case-insensitive.
86+
Observe que ambas `match:Nós` e `match:nós` são encontradas, porque flag `pattern:i` torna a expressão regular sem distinção entre maiúsculas e minúsculas.
8787

88-
2. If there's no such flag it returns only the first match in the form of an array, with the full match at index `0` and some additional details in properties:
88+
2. Se não houver essa flag, ela retornará apenas a primeira correspondência na forma de uma matriz, com a correspondência completa no índice `0` e alguns detalhes adicionais nas propriedades:
8989
```js run
90-
let str = "We will, we will rock you";
90+
let str = "Nós vamos, nós vamos sacudir você";
9191
92-
let result = str.match(/we/i); // without flag g
92+
let result = str.match(/nós/i); // sem flag g
9393
94-
alert( result[0] ); // We (1st match)
94+
alert( result[0] ); // Nós (1º correspondência)
9595
alert( result.length ); // 1
9696
97-
// Details:
98-
alert( result.index ); // 0 (position of the match)
99-
alert( result.input ); // We will, we will rock you (source string)
97+
// Detalhes:
98+
alert( result.index ); // 0 (posição da correspondência)
99+
alert( result.input ); // Nós vamos, nós vamos sacudir você (string de origem)
100100
```
101-
The array may have other indexes, besides `0` if a part of the regular expression is enclosed in parentheses. We'll cover that in the chapter <info:regexp-groups>.
101+
A matriz pode ter outros índices, além de `0` se uma parte da expressão regular estiver entre parênteses. Abordaremos isso no capítulo <info:regexp-groups>.
102102

103-
3. And, finally, if there are no matches, `null` is returned (doesn't matter if there's flag `pattern:g` or not).
103+
3. E, finalmente, se não houver correspondências, `null` é retornado (não importa se há flags `pattern:g` ou não).
104104

105-
This a very important nuance. If there are no matches, we don't receive an empty array, but instead receive `null`. Forgetting about that may lead to errors, e.g.:
105+
Esta é uma nuance muito importante. Se não houver correspondências, não receberemos uma matriz vazia, mas receberemos `null`. Esquecer isso pode levar a erros, por exemplo:
106106

107107
```js run
108108
let matches = "JavaScript".match(/HTML/); // = null
109109
110110
if (!matches.length) { // Error: Cannot read property 'length' of null
111-
alert("Error in the line above");
111+
alert("Erro na linha acima");
112112
}
113113
```
114114

115-
If we'd like the result to always be an array, we can write it this way:
115+
Se quisermos que o resultado seja sempre uma matriz, podemos escrevê-lo desta maneira:
116116

117117
```js run
118-
let matches = "JavaScript".match(/HTML/)*!* || []*/!*;
118+
let matches = "JavaScript".match(/HTML/) || [];
119119
120120
if (!matches.length) {
121-
alert("No matches"); // now it works
121+
alert("Sem correspondências"); // agora funciona
122122
}
123123
```
124124

125-
## Replacing: str.replace
125+
## Substituindo: str.replace
126126

127-
The method `str.replace(regexp, replacement)` replaces matches found using `regexp` in string `str` with `replacement` (all matches if there's flag `pattern:g`, otherwise, only the first one).
127+
O método `str.replace(regexp, substituição)` substitui as correspondências encontradas usando `regexp` na string ` str` por `substituição` (todas as correspondências se houver flag `pattern:g`, caso contrário, apenas a primeira).
128128

129-
For instance:
129+
Por exemplo:
130130

131131
```js run
132-
// no flag g
133-
alert( "We will, we will".replace(/we/i, "I") ); // I will, we will
132+
// sem flag g
133+
alert( "Nós vamos, nós vamos".replace(/nós/i, "Eu") ); // Eu vamos, nós vamos
134134
135-
// with flag g
136-
alert( "We will, we will".replace(/we/ig, "I") ); // I will, I will
135+
// com flag g
136+
alert( "Nós vamos, nós vamos".replace(/nós/ig, "Eu") ); // Eu vamos, Eu vamos
137137
```
138138

139-
The second argument is the `replacement` string. We can use special character combinations in it to insert fragments of the match:
139+
O segundo argumento é a string de `substituição`. Podemos usar combinações especiais de caracteres para inserir fragmentos da correspondência:
140140

141-
| Symbols | Action in the replacement string |
141+
| Símbolos | Ação na string de substituição |
142142
|--------|--------|
143-
|`$&`|inserts the whole match|
144-
|<code>$&#096;</code>|inserts a part of the string before the match|
145-
|`$'`|inserts a part of the string after the match|
146-
|`$n`|if `n` is a 1-2 digit number, then it inserts the contents of n-th parentheses, more about it in the chapter <info:regexp-groups>|
147-
|`$<name>`|inserts the contents of the parentheses with the given `name`, more about it in the chapter <info:regexp-groups>|
148-
|`$$`|inserts character `$` |
143+
|`$&`|insere toda a correspondência|
144+
|<code>$&#096;</code>|insere uma parte da string antes da correspondência|
145+
|`$'`|insere uma parte da string depois da correspondência|
146+
|`$n`|se `n` for um número de 1-2 dígitos, ela inserirá o conteúdo dos enésimos parênteses, mais sobre isso no capítulo <info:regexp-groups>|
147+
|`$<nome>`|insere o conteúdo dos parênteses com o `nome` fornecido, mais sobre isso no capítulo <info:regexp-groups>|
148+
|`$$`|insere o caractere `$` |
149149

150-
An example with `pattern:$&`:
150+
Um exemplo com o `pattern:$&`:
151151

152152
```js run
153-
alert( "I love HTML".replace(/HTML/, "$& and JavaScript") ); // I love HTML and JavaScript
153+
alert( "Eu amo HTML".replace(/HTML/, "$& e JavaScript") ); // Eu amo HTML e JavaScript
154154
```
155155

156-
## Testing: regexp.test
156+
## Teste: regexp.test
157157

158-
The method `regexp.test(str)` looks for at least one match, if found, returns `true`, otherwise `false`.
158+
O método `regexp.test(str)` procura pelo menos uma correspondência, se encontrada, retorna `true`, caso contrário,`false`.
159159

160160
```js run
161-
let str = "I love JavaScript";
162-
let regexp = /LOVE/i;
161+
let str = "Eu amo JavaScript";
162+
let regexp = /AMO/i;
163163
164164
alert( regexp.test(str) ); // true
165165
```
166166

167-
Later in this chapter we'll study more regular expressions, walk through more examples, and also meet other methods.
167+
Mais adiante neste capítulo, estudaremos mais expressões regulares, examinaremos mais exemplos e também conheceremos outros métodos.
168168

169-
Full information about the methods is given in the article <info:regexp-methods>.
169+
Informações completas sobre os métodos são fornecidas no artigo <info:regexp-methods>.
170170

171-
## Summary
171+
## Resumo
172172

173-
- A regular expression consists of a pattern and optional flags: `pattern:g`, `pattern:i`, `pattern:m`, `pattern:u`, `pattern:s`, `pattern:y`.
174-
- Without flags and special symbols (that we'll study later), the search by a regexp is the same as a substring search.
175-
- The method `str.match(regexp)` looks for matches: all of them if there's `pattern:g` flag, otherwise, only the first one.
176-
- The method `str.replace(regexp, replacement)` replaces matches found using `regexp` with `replacement`: all of them if there's `pattern:g` flag, otherwise only the first one.
177-
- The method `regexp.test(str)` returns `true` if there's at least one match, otherwise, it returns `false`.
173+
- Uma expressão regular consiste em um padrão e flags opcionais: `pattern:g`, `pattern:i`, `pattern:m`, `pattern:u`, `pattern:s`, `pattern:y`.
174+
- Sem flags e símbolos especiais (que estudaremos mais adiante), a pesquisa por uma regexp é igual à pesquisa com substring.
175+
- O método `str.match(regexp)` procura por correspondências: todas elas se houver a flag `pattern:g`, caso contrário, apenas a primeira.
176+
- O método `str.replace(regexp, substituição)` substitui as correspondências encontradas usando `regexp` por 'substituição': todas elas se houver uma flag `pattern:g`, caso contrário, somente a primeira.
177+
- O método `regexp.test(str)` retorna `true` se houver pelo menos uma correspondência, caso contrário, retorna `false`.

0 commit comments

Comments
 (0)