- Notifications
You must be signed in to change notification settings - Fork111
Escaping, special characters#425
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 ourterms of service andprivacy statement. We’ll occasionally send you account related emails.
Already on GitHub?Sign in to your account
Open
peruibeloko wants to merge2 commits intojavascript-tutorial:masterChoose a base branch fromperuibeloko:09/07
base:master
Could not load branches
Branch not found:{{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline, and old review comments may become outdated.
Uh oh!
There was an error while loading.Please reload this page.
Open
Changes fromall commits
Commits
Show all changes
2 commits Select commitHold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading.Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading.Please reload this page.
Diff view
Diff view
There are no files selected for viewing
80 changes: 40 additions & 40 deletions9-regular-expressions/07-regexp-escaping/article.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,99 +1,99 @@ | ||
# Escapes, caracteres especiais | ||
Como vimos anteriormente, a contrabarra `pattern:\` é usada para demarcar classes de caracteres, como `pattern:\d` por exemplo. Sendo então, um caractere especial em regexes (bem como em strings normais). | ||
Existem outros caracteres especiais que também tem significados especias numa regex, como `pattern:[ ] { } ( ) \ ^ $ . | ? * +`. Esses são usados para realizar buscas mais poderosas. | ||
Não tente decorar a lista -- em breve vamos cobrir cada um deles, e no processo você irá decorá-los automaticamente. | ||
## Escapes | ||
Digamos que precisamos buscar um ponto '.' literal. Não "qualquer caractere", apenas um ponto. | ||
Para usar um caractere especial como um caractere comum, adicionamos uma contrabarra dessa forma: `pattern:\.`. | ||
Isso também é conhecido como "escapar um caractere". | ||
Por exemplo: | ||
```js run | ||
alert("Chapter 5.1".match(/\d\.\d/)); // 5.1 (match!) | ||
alert("Chapter 511".match(/\d\.\d/)); // null (procurando por um ponto literal \.) | ||
``` | ||
Parênteses também são caracteres especiais, então se quisermos usá-los, devemos usar`pattern:\(`.O exemplo abaixo procura a string `"g()"`: | ||
```js run | ||
alert("function g()".match(/g\(\)/)); // "g()" | ||
``` | ||
Se estivermos buscando por uma contrabarra `\`,que é um caractere especial tanto em stringscomuns quanto em regexes, devemos escapá-la também. | ||
```js run | ||
alert("1\\2".match(/\\/)); // '\' | ||
``` | ||
##Uma barra | ||
O caractere de barra`'/'`não é um caractere especial, mas no JavaScripté usado para delimitar regexes: `pattern:/...pattern.../`,então devemos escapá-la também. | ||
Uma busca por uma barra`'/'`fica assim: | ||
```js run | ||
alert("/".match(/\//)); // '/' | ||
``` | ||
Por outro lado, se não estivermos usando a sintaxe`pattern:/.../`,mas sim o construtor`new RegExp`,não é necessário usar um escape: | ||
```js run | ||
alert("/".match(new RegExp("/"))); //busca um / | ||
``` | ||
## new RegExp | ||
Se estivermos criando uma expressão regularcom o `new RegExp`,não precisamos escapar o`/`,mas precisamos aplicar outros escapes. | ||
Considere esse exemplo: | ||
```js run | ||
let regexp = new RegExp("d.d"); | ||
alert("Chapter 5.1".match(regexp)); // null | ||
``` | ||
Uma busca muitosimilarem um dos exemplos anteriores funcionou com o `pattern:/\d\.\d/`,mas nosso`new RegExp("\d\.\d")`não. Por quê? | ||
Isso acontece porque contrabarras são "consumidas" pelastring.Como deve se lembrar,stringscomuns tem seus próprios caracteres especiais, como o `\n`,e contrabarras são usadas para escapes. | ||
Veja como "\d\.\d"é interpretado: | ||
```js run | ||
alert("d.d"); // d.d | ||
``` | ||
Strings comuns "consomem" contrabarras e interpretam-nas separadamente, por exemplo: | ||
- `\n` --se torna um caractere de quebra de linha, | ||
- `\u1234` --se torna o caractereUnicodecom o código fornecido, | ||
- ...E quando não há nenhum significado especial, como`pattern:\d`ou `\z`,a contrabarra é simplesmente removida. | ||
Então `new RegExp`recebe uma stringsem contrabarras. Por isso que a busca não funciona! | ||
Para consertar isso, precisamos escapar a contrabarra, já que strings comuns tornam`\\`em `\`: | ||
```js run | ||
*!* | ||
let regStr = "\\d\\.\\d"; | ||
*/!* | ||
alert(regStr); // \d\.\d (correto) | ||
let regexp = new RegExp(regStr); | ||
alert( "Chapter 5.1".match(regexp) ); // 5.1 | ||
``` | ||
##Resumo | ||
-Para usar caracteres especiais`pattern:[ \ ^ $ . | ? * + ( )`de maneira literal, precisamos usar a contrabarra `\` ("escapar os caracteres"). | ||
-Nós também precisamos escapar a `/`se estivermos dentro do`pattern:/.../` (mas não do `new RegExp`). | ||
-Quando passarmos uma stringpara `new RegExp`,precisamos escapar contrabarras, (`\\`) já que strings consomem uma delas. |
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.