Skip to content

Commit c3e18a3

Browse files
authored
Merge pull request #425 from peruibeloko/09/07
Escaping, special characters
2 parents 691605d + a228840 commit c3e18a3

File tree

1 file changed

+40
-40
lines changed
  • 9-regular-expressions/07-regexp-escaping

1 file changed

+40
-40
lines changed
Lines changed: 40 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -1,99 +1,99 @@
1+
# Escapes, caracteres especiais
12

2-
# Escaping, special characters
3+
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).
34

4-
As we've seen, a backslash `pattern:\` is used to denote character classes, e.g. `pattern:\d`. So it's a special character in regexps (just like in regular strings).
5+
Existem outros caracteres especiais que também tem significados especias numa regex, como `pattern:[ ] { } ( ) \ ^ $ . | ? * +`. Esses são usados para realizar buscas mais poderosas.
56

6-
There are other special characters as well, that have special meaning in a regexp, such as `pattern:[ ] { } ( ) \ ^ $ . | ? * +`. They are used to do more powerful searches.
7+
Não tente decorar a lista -- em breve vamos cobrir cada um deles, e no processo você irá decorá-los automaticamente.
78

8-
Don't try to remember the list -- soon we'll deal with each of them, and you'll know them by heart automatically.
9+
## Escapes
910

10-
## Escaping
11+
Digamos que precisamos buscar um ponto '.' literal. Não "qualquer caractere", apenas um ponto.
1112

12-
Let's say we want to find literally a dot. Not "any character", but just a dot.
13+
Para usar um caractere especial como um caractere comum, adicionamos uma contrabarra dessa forma: `pattern:\.`.
1314

14-
To use a special character as a regular one, prepend it with a backslash: `pattern:\.`.
15+
Isso também é conhecido como "escapar um caractere".
1516

16-
That's also called "escaping a character".
17+
Por exemplo:
1718

18-
For example:
1919
```js run
20-
alert( "Chapter 5.1".match(/\d\.\d/) ); // 5.1 (match!)
21-
alert( "Chapter 511".match(/\d\.\d/) ); // null (looking for a real dot \.)
20+
alert("Chapter 5.1".match(/\d\.\d/)); // 5.1 (match!)
21+
alert("Chapter 511".match(/\d\.\d/)); // null (procurando por um ponto literal \.)
2222
```
2323

24-
Parentheses are also special characters, so if we want them, we should use `pattern:\(`. The example below looks for a string `"g()"`:
24+
Parênteses também são caracteres especiais, então se quisermos usá-los, devemos usar `pattern:\(`. O exemplo abaixo procura a string `"g()"`:
2525

2626
```js run
27-
alert( "function g()".match(/g\(\)/) ); // "g()"
27+
alert("function g()".match(/g\(\)/)); // "g()"
2828
```
2929

30-
If we're looking for a backslash `\`, it's a special character in both regular strings and regexps, so we should double it.
30+
Se estivermos buscando por uma contrabarra `\`, que é um caractere especial tanto em strings comuns quanto em regexes, devemos escapá-la também.
3131

3232
```js run
33-
alert( "1\\2".match(/\\/) ); // '\'
33+
alert("1\\2".match(/\\/)); // '\'
3434
```
3535

36-
## A slash
36+
## Uma barra
3737

38-
A slash symbol `'/'` is not a special character, but in JavaScript it is used to open and close the regexp: `pattern:/...pattern.../`, so we should escape it too.
38+
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.
3939

40-
Here's what a search for a slash `'/'` looks like:
40+
Uma busca por uma barra `'/'` fica assim:
4141

4242
```js run
43-
alert( "/".match(/\//) ); // '/'
43+
alert("/".match(/\//)); // '/'
4444
```
4545

46-
On the other hand, if we're not using `pattern:/.../`, but create a regexp using `new RegExp`, then we don't need to escape it:
46+
Por outro lado, se não estivermos usando a sintaxe `pattern:/.../`, mas sim o construtor `new RegExp`, não é necessário usar um escape:
4747

4848
```js run
49-
alert( "/".match(new RegExp("/")) ); // finds /
49+
alert("/".match(new RegExp("/"))); // busca um /
5050
```
5151

5252
## new RegExp
5353

54-
If we are creating a regular expression with `new RegExp`, then we don't have to escape `/`, but need to do some other escaping.
54+
Se estivermos criando uma expressão regular com o `new RegExp`, não precisamos escapar o `/`, mas precisamos aplicar outros escapes.
5555

56-
For instance, consider this:
56+
Considere esse exemplo:
5757

5858
```js run
59-
let regexp = new RegExp("\d\.\d");
59+
let regexp = new RegExp("d.d");
6060

61-
alert( "Chapter 5.1".match(regexp) ); // null
61+
alert("Chapter 5.1".match(regexp)); // null
6262
```
6363

64-
The similar search in one of previous examples worked with `pattern:/\d\.\d/`, but `new RegExp("\d\.\d")` doesn't work, why?
64+
Uma busca muito similar em um dos exemplos anteriores funcionou com o `pattern:/\d\.\d/`, mas nosso `new RegExp("\d\.\d")` não. Por quê?
6565

66-
The reason is that backslashes are "consumed" by a string. As we may recall, regular strings have their own special characters, such as `\n`, and a backslash is used for escaping.
66+
Isso acontece porque contrabarras são "consumidas" pela string. Como deve se lembrar, strings comuns tem seus próprios caracteres especiais, como o `\n`, e contrabarras são usadas para escapes.
6767

68-
Here's how "\d\.\d" is perceived:
68+
Veja como "\d\.\d" é interpretado:
6969

7070
```js run
71-
alert("\d\.\d"); // d.d
71+
alert("d.d"); // d.d
7272
```
7373

74-
String quotes "consume" backslashes and interpret them on their own, for instance:
74+
Strings comuns "consomem" contrabarras e interpretam-nas separadamente, por exemplo:
7575

76-
- `\n` -- becomes a newline character,
77-
- `\u1234` -- becomes the Unicode character with such code,
78-
- ...And when there's no special meaning: like `pattern:\d` or `\z`, then the backslash is simply removed.
76+
- `\n` -- se torna um caractere de quebra de linha,
77+
- `\u1234` -- se torna o caractere Unicode com o código fornecido,
78+
- ...E quando não há nenhum significado especial, como `pattern:\d` ou `\z`, a contrabarra é simplesmente removida.
7979

80-
So `new RegExp` gets a string without backslashes. That's why the search doesn't work!
80+
Então `new RegExp` recebe uma string sem contrabarras. Por isso que a busca não funciona!
8181

82-
To fix it, we need to double backslashes, because string quotes turn `\\` into `\`:
82+
Para consertar isso, precisamos escapar a contrabarra, já que strings comuns tornam `\\` em `\`:
8383

8484
```js run
8585
*!*
8686
let regStr = "\\d\\.\\d";
8787
*/!*
88-
alert(regStr); // \d\.\d (correct now)
88+
alert(regStr); // \d\.\d (correto)
8989

9090
let regexp = new RegExp(regStr);
9191

9292
alert( "Chapter 5.1".match(regexp) ); // 5.1
9393
```
9494

95-
## Summary
95+
## Resumo
9696

97-
- To search for special characters `pattern:[ \ ^ $ . | ? * + ( )` literally, we need to prepend them with a backslash `\` ("escape them").
98-
- We also need to escape `/` if we're inside `pattern:/.../` (but not inside `new RegExp`).
99-
- When passing a string to `new RegExp`, we need to double backslashes `\\`, cause string quotes consume one of them.
97+
- Para usar caracteres especiais `pattern:[ \ ^ $ . | ? * + ( )` de maneira literal, precisamos usar a contrabarra `\` ("escapar os caracteres").
98+
- Nós também precisamos escapar a `/` se estivermos dentro do `pattern:/.../` (mas não do `new RegExp`).
99+
- Quando passarmos uma string para `new RegExp`, precisamos escapar contrabarras, (`\\`) já que strings consomem uma delas.

0 commit comments

Comments
 (0)