-
-
Notifications
You must be signed in to change notification settings - Fork 113
Patterns and flags #147
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Patterns and flags #147
Changes from 3 commits
efa4871
b707c26
b45e0db
e3fbf39
2e57ce5
a27c352
7481795
9166ab4
c061b7a
4f5464d
3b1b03f
48e7e8c
d3d72e3
91686e7
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change | ||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| @@ -1,177 +1,177 @@ | ||||||||||
| # Patterns and flags | ||||||||||
| # Padrões e flags | ||||||||||
|
|
||||||||||
| Regular expressions are patterns that provide a powerful way to search and replace in text. | ||||||||||
| Expressões regulares são padrões que fornecem uma maneira poderosa de pesquisar e substituir no texto. | ||||||||||
|
|
||||||||||
| In JavaScript, they are available via the [RegExp](mdn:js/RegExp) object, as well as being integrated in methods of strings. | ||||||||||
| Em JavaScript, elas estão disponíveis através do objeto [RegExp](mdn:js/RegExp), além de serem integradas aos métodos de strings. | ||||||||||
|
|
||||||||||
| ## Regular Expressions | ||||||||||
| ## Expressões regulares | ||||||||||
|
|
||||||||||
| A regular expression (also "regexp", or just "reg") consists of a *pattern* and optional *flags*. | ||||||||||
| Uma expressão regular (também "regexp" ou apenas "reg") consiste em um *padrão* e *flags* opcionais. | ||||||||||
|
|
||||||||||
| There are two syntaxes that can be used to create a regular expression object. | ||||||||||
| Existem duas sintaxes que podem ser usadas para criar um objeto de expressão regular. | ||||||||||
|
|
||||||||||
| The "long" syntax: | ||||||||||
| A sintaxe "longa": | ||||||||||
|
|
||||||||||
| ```js | ||||||||||
| regexp = new RegExp("pattern", "flags"); | ||||||||||
| regexp = new RegExp("padrão", "flags"); | ||||||||||
| ``` | ||||||||||
|
|
||||||||||
| And the "short" one, using slashes `"/"`: | ||||||||||
| E a "curta", usando barras `"/"`: | ||||||||||
|
|
||||||||||
| ```js | ||||||||||
| regexp = /pattern/; // no flags | ||||||||||
| regexp = /pattern/gmi; // with flags g,m and i (to be covered soon) | ||||||||||
| regexp = /padrão/; // sem flags | ||||||||||
| regexp = /padrão/gmi; // com flags `g`, `m` e `i` (a ser abordado em breve) | ||||||||||
| ``` | ||||||||||
|
|
||||||||||
| Slashes `pattern:/.../` tell JavaScript that we are creating a regular expression. They play the same role as quotes for strings. | ||||||||||
| Barras `padrão:/.../` informam ao JavaScript que estamos criando uma expressão regular. Eles desempenham o mesmo papel que aspas para strings. | ||||||||||
|
|
||||||||||
| In both cases `regexp` becomes an instance of the built-in `RegExp` class. | ||||||||||
| Em ambos os casos, a `regexp` se torna uma instância da classe interna `RegExp`. | ||||||||||
odsantos marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||||||||||
|
|
||||||||||
| 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. | ||||||||||
| 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. | ||||||||||
|
|
||||||||||
| 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: | ||||||||||
| 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: | ||||||||||
|
|
||||||||||
| ```js | ||||||||||
| let tag = prompt("What tag do you want to find?", "h2"); | ||||||||||
| let tag = prompt("Qual tag você deseja encontrar?", "h2"); | ||||||||||
|
|
||||||||||
| let regexp = new RegExp(`<${tag}>`); // same as /<h2>/ if answered "h2" in the prompt above | ||||||||||
| let regexp = new RegExp(`<${tag}>`); // igual a /<h2>/ se respondeu "h2" no prompt acima | ||||||||||
| ``` | ||||||||||
|
|
||||||||||
| ## Flags | ||||||||||
|
|
||||||||||
| Regular expressions may have flags that affect the search. | ||||||||||
| Expressões regulares podem ter flags que afetam a pesquisa. | ||||||||||
|
|
||||||||||
| There are only 6 of them in JavaScript: | ||||||||||
| Existem apenas 6 delas em JavaScript: | ||||||||||
|
|
||||||||||
| `pattern:i` | ||||||||||
| : With this flag the search is case-insensitive: no difference between `A` and `a` (see the example below). | ||||||||||
| `padrão:i` | ||||||||||
| : 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). | ||||||||||
|
|
||||||||||
| `pattern:g` | ||||||||||
| : With this flag the search looks for all matches, without it -- only the first match is returned. | ||||||||||
| `padrão:g` | ||||||||||
| : Com essa flag, a pesquisa procura todas as correspondências, sem ela - somente a primeira correspondência é retornada. | ||||||||||
|
|
||||||||||
| `pattern:m` | ||||||||||
| : Multiline mode (covered in the chapter <info:regexp-multiline-mode>). | ||||||||||
| `padrão:m` | ||||||||||
| : Modo multilinha (abordado no capítulo <info:regexp-multiline-mode>). | ||||||||||
|
|
||||||||||
| `pattern:s` | ||||||||||
| : Enables "dotall" mode, that allows a dot `pattern:.` to match newline character `\n` (covered in the chapter <info:regexp-character-classes>). | ||||||||||
| `padrão:s` | ||||||||||
| : Ativa o modo "dotall", que permite que um ponto `padrão:.` corresponda ao caractere de nova linha `\n` (abordado no capítulo <info:regexp-character-classes>). | ||||||||||
|
|
||||||||||
| `pattern:u` | ||||||||||
| : Enables full Unicode support. The flag enables correct processing of surrogate pairs. More about that in the chapter <info:regexp-unicode>. | ||||||||||
| `padrão:u` | ||||||||||
| : Ativa o suporte completo a unicode. A flag permite o processamento correto de pares substitutos. Mais sobre isso no capítulo <info:regexp-unicode>. | ||||||||||
odsantos marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||||||||||
|
|
||||||||||
| `pattern:y` | ||||||||||
| : "Sticky" mode: searching at the exact position in the text (covered in the chapter <info:regexp-sticky>) | ||||||||||
| `padrão:y` | ||||||||||
| : Modo "Fixo": pesquisando na posição exata no texto (abordado no capítulo <info:regexp-sticky>) | ||||||||||
odsantos marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||||||||||
|
|
||||||||||
| ```smart header="Colors" | ||||||||||
| From here on the color scheme is: | ||||||||||
| ```smart header="Cores" | ||||||||||
| A partir daqui, o esquema de cores é: | ||||||||||
|
|
||||||||||
| - regexp -- `pattern:red` | ||||||||||
| - string (where we search) -- `subject:blue` | ||||||||||
| - result -- `match:green` | ||||||||||
| - regexp -- `padrão:vermelho` | ||||||||||
| - string (onde pesquisamos) -- `sujeito:azul` | ||||||||||
odsantos marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||||||||||
| - result -- `correspondência:verde` | ||||||||||
| ``` | ||||||||||
|
|
||||||||||
| ## Searching: str.match | ||||||||||
| ## Pesquisando: str.match | ||||||||||
|
|
||||||||||
| As mentioned previously, regular expressions are integrated with string methods. | ||||||||||
| Como mencionado anteriormente, expressões regulares são integradas a métodos de string. | ||||||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
Suggested change
|
||||||||||
|
|
||||||||||
| The method `str.match(regexp)` finds all matches of `regexp` in the string `str`. | ||||||||||
| O método `str.match(regexp)` encontra todas as correspondências de `regexp` na string `str`. | ||||||||||
|
|
||||||||||
| It has 3 working modes: | ||||||||||
| Possui 3 modos de trabalho: | ||||||||||
|
|
||||||||||
| 1. If the regular expression has flag `pattern:g`, it returns an array of all matches: | ||||||||||
| 1. Se a expressão regular tiver flag `padrão:g`, ela retornará uma matriz de todas as correspondências: | ||||||||||
|
||||||||||
| 1. Se a expressão regular tiver flag `padrão:g`, ela retornará uma matriz de todas as correspondências: | |
| 1. Se a expressão regular tiver a flag `padrão:g`, ela retornará uma matriz com todas as correspondências: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
| let str = "Nós vamos, nós vamos sacudir você"; | |
| let str = "Nós vamos, nós vamos baloiçar você"; |
Outdated
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
| Observe que ambas `correspondência:Nós` e `correspondência:nós` são encontradas, porque flag `padrão:i` torna a expressão regular sem distinção entre maiúsculas e minúsculas. | |
| Observe que ambas `correspondência:Nós` e `correspondência:nós` são encontradas, porque a flag `padrão:i` torna a expressão regular sem distinção entre maiúsculas e minúsculas. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
| let str = "Nós vamos, nós vamos sacudir você"; | |
| let str = "Nós vamos, nós vamos baloiçar você"; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
| alert( result.input ); // Nós vamos, nós vamos sacudir você (string de origem) | |
| alert( result.input ); // Nós vamos, nós vamos baloiçar você (string de origem) |
Outdated
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
| 3. E, finalmente, se não houver correspondências, `null` é retornado (não importa se há flags `padrão:g` ou não). | |
| 3. E, finalmente, se não houver correspondências, `null` é retornado (não importa se há a flag `padrão:g` ou não). |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
| if (!matches.length) { // Error: Cannot read property 'length' of null | |
| if (!matches.length) { // Error: Cannot read property 'length' of null (Erro: Não é possível ler a propriedade 'length' de null) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
| let matches = "JavaScript".match(/HTML/) || []; | |
| let matches = "JavaScript".match(/HTML/)*!* || []*/!*; |
Outdated
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
| 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 `padrão:g`, caso contrário, apenas a primeira). | |
| 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 a flag `padrão:g`, caso contrário, apenas a primeira). |
Uh oh!
There was an error while loading. Please reload this page.