|
1 |
| -# Patterns and flags |
| 1 | +# Padrões e flags |
2 | 2 |
|
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. |
4 | 4 |
|
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. |
6 | 6 |
|
7 |
| -## Regular Expressions |
| 7 | +## Expressões regulares |
8 | 8 |
|
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. |
10 | 10 |
|
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. |
12 | 12 |
|
13 |
| -The "long" syntax: |
| 13 | +A sintaxe "longa": |
14 | 14 |
|
15 | 15 | ```js
|
16 |
| -regexp = new RegExp("pattern", "flags"); |
| 16 | +regexp = new RegExp("padrão", "flags"); |
17 | 17 | ```
|
18 | 18 |
|
19 |
| -And the "short" one, using slashes `"/"`: |
| 19 | +E a "curta", usando barras `"/"`: |
20 | 20 |
|
21 | 21 | ```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) |
24 | 24 | ```
|
25 | 25 |
|
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. |
27 | 27 |
|
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`. |
29 | 29 |
|
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. |
31 | 31 |
|
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: |
33 | 33 |
|
34 | 34 | ```js
|
35 |
| -let tag = prompt("What tag do you want to find?", "h2"); |
| 35 | +let tag = prompt("Qual tag você deseja encontrar?", "h2"); |
36 | 36 |
|
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 |
38 | 38 | ```
|
39 | 39 |
|
40 | 40 | ## Flags
|
41 | 41 |
|
42 |
| -Regular expressions may have flags that affect the search. |
| 42 | +Expressões regulares podem ter flags que afetam a pesquisa. |
43 | 43 |
|
44 |
| -There are only 6 of them in JavaScript: |
| 44 | +Existem apenas 6 delas em JavaScript: |
45 | 45 |
|
46 | 46 | `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). |
48 | 48 |
|
49 | 49 | `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. |
51 | 51 |
|
52 | 52 | `pattern:m`
|
53 |
| -: Multiline mode (covered in the chapter <info:regexp-multiline-mode>). |
| 53 | +: Modo multilinha (abordado no capítulo <info:regexp-multiline-mode>). |
54 | 54 |
|
55 | 55 | `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>). |
57 | 57 |
|
58 | 58 | `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>. |
60 | 60 |
|
61 | 61 | `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>) |
63 | 63 |
|
64 |
| -```smart header="Colors" |
65 |
| -From here on the color scheme is: |
| 64 | +```smart header="Cores" |
| 65 | +A partir daqui, o esquema de cores é: |
66 | 66 |
|
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` |
70 | 70 | ```
|
71 | 71 |
|
72 |
| -## Searching: str.match |
| 72 | +## Pesquisando: str.match |
73 | 73 |
|
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. |
75 | 75 |
|
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`. |
77 | 77 |
|
78 |
| -It has 3 working modes: |
| 78 | +Possui 3 modos de trabalho: |
79 | 79 |
|
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: |
81 | 81 | ```js run
|
82 |
| - let str = "We will, we will rock you"; |
| 82 | + let str = "Nós vamos, nós vamos sacudir você"; |
83 | 83 |
|
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) |
85 | 85 | ```
|
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. |
87 | 87 |
|
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: |
89 | 89 | ```js run
|
90 |
| - let str = "We will, we will rock you"; |
| 90 | + let str = "Nós vamos, nós vamos sacudir você"; |
91 | 91 |
|
92 |
| - let result = str.match(/we/i); // without flag g |
| 92 | + let result = str.match(/nós/i); // sem flag g |
93 | 93 |
|
94 |
| - alert( result[0] ); // We (1st match) |
| 94 | + alert( result[0] ); // Nós (1º correspondência) |
95 | 95 | alert( result.length ); // 1
|
96 | 96 |
|
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) |
100 | 100 | ```
|
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>. |
102 | 102 |
|
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). |
104 | 104 |
|
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: |
106 | 106 |
|
107 | 107 | ```js run
|
108 | 108 | let matches = "JavaScript".match(/HTML/); // = null
|
109 | 109 |
|
110 | 110 | if (!matches.length) { // Error: Cannot read property 'length' of null
|
111 |
| - alert("Error in the line above"); |
| 111 | + alert("Erro na linha acima"); |
112 | 112 | }
|
113 | 113 | ```
|
114 | 114 |
|
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: |
116 | 116 |
|
117 | 117 | ```js run
|
118 |
| - let matches = "JavaScript".match(/HTML/)*!* || []*/!*; |
| 118 | + let matches = "JavaScript".match(/HTML/) || []; |
119 | 119 |
|
120 | 120 | if (!matches.length) {
|
121 |
| - alert("No matches"); // now it works |
| 121 | + alert("Sem correspondências"); // agora funciona |
122 | 122 | }
|
123 | 123 | ```
|
124 | 124 |
|
125 |
| -## Replacing: str.replace |
| 125 | +## Substituindo: str.replace |
126 | 126 |
|
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). |
128 | 128 |
|
129 |
| -For instance: |
| 129 | +Por exemplo: |
130 | 130 |
|
131 | 131 | ```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 |
134 | 134 |
|
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 |
137 | 137 | ```
|
138 | 138 |
|
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: |
140 | 140 |
|
141 |
| -| Symbols | Action in the replacement string | |
| 141 | +| Símbolos | Ação na string de substituição | |
142 | 142 | |--------|--------|
|
143 |
| -|`$&`|inserts the whole match| |
144 |
| -|<code>$`</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>$`</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 `$` | |
149 | 149 |
|
150 |
| -An example with `pattern:$&`: |
| 150 | +Um exemplo com o `pattern:$&`: |
151 | 151 |
|
152 | 152 | ```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 |
154 | 154 | ```
|
155 | 155 |
|
156 |
| -## Testing: regexp.test |
| 156 | +## Teste: regexp.test |
157 | 157 |
|
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`. |
159 | 159 |
|
160 | 160 | ```js run
|
161 |
| -let str = "I love JavaScript"; |
162 |
| -let regexp = /LOVE/i; |
| 161 | +let str = "Eu amo JavaScript"; |
| 162 | +let regexp = /AMO/i; |
163 | 163 |
|
164 | 164 | alert( regexp.test(str) ); // true
|
165 | 165 | ```
|
166 | 166 |
|
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. |
168 | 168 |
|
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>. |
170 | 170 |
|
171 |
| -## Summary |
| 171 | +## Resumo |
172 | 172 |
|
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