Skip to content

Commit 24b8013

Browse files
committed
Revert "Merge branch 'fsdude-02-regexp-character-classes' into master"
This reverts commit 41188c4, reversing changes made to 0c959f9.
1 parent 72ffd48 commit 24b8013

File tree

1 file changed

+79
-79
lines changed
  • 9-regular-expressions/02-regexp-character-classes

1 file changed

+79
-79
lines changed
Lines changed: 79 additions & 79 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
1-
# Classes de caracteres
1+
# Character classes
22

3-
Considere uma tarefa prática - temos um número de telefone como `"+7(903)-123-45-67"` e precisamos transformá-lo em números puros: `79031234567`.
3+
Consider a practical task -- we have a phone number like `"+7(903)-123-45-67"`, and we need to turn it into pure numbers: `79031234567`.
44

5-
Para fazer isso, podemos encontrar e remover qualquer coisa que não seja um número. Classes de personagens podem ajudar com isso.
5+
To do so, we can find and remove anything that's not a number. Character classes can help with that.
66

7-
Uma *classe de caracteres* é uma notação especial que corresponde a qualquer símbolo de um determinado conjunto.
7+
A *character class* is a special notation that matches any symbol from a certain set.
88

9-
Para começar, vamos explorar a classe "digit". Está escrito como `padrão: \d` e corresponde a "qualquer dígito único".
9+
For the start, let's explore the "digit" class. It's written as `pattern:\d` and corresponds to "any single digit".
1010

11-
Por exemplo, vamos encontrar o primeiro dígito no número de telefone:
11+
For instance, let's find the first digit in the phone number:
1212

1313
```js run
1414
let str = "+7(903)-123-45-67";
@@ -18,186 +18,186 @@ let regexp = /\d/;
1818
alert( str.match(regexp) ); // 7
1919
```
2020

21-
Sem a flag `padrão:g`, a expressão regular procura apenas a primeira correspondência, que é o primeiro dígito `padrão:\d`.
21+
Without the flag `pattern:g`, the regular expression only looks for the first match, that is the first digit `pattern:\d`.
2222

23-
Vamos adicionar a flag `padrão:g` para encontrar todos os dígitos:
23+
Let's add the `pattern:g` flag to find all digits:
2424

2525
```js run
2626
let str = "+7(903)-123-45-67";
2727

2828
let regexp = /\d/g;
2929

30-
alert( str.match(regexp) ); // matriz de correspondências: 7,9,0,3,1,2,3,4,5,6,7
30+
alert( str.match(regexp) ); // array of matches: 7,9,0,3,1,2,3,4,5,6,7
3131

32-
// vamos criar o número de telefone apenas com dígitos:
32+
// let's make the digits-only phone number of them:
3333
alert( str.match(regexp).join('') ); // 79031234567
3434
```
3535

36-
Essa era uma classe de caracteres para dígitos. Existem outras classes de caracteres também.
36+
That was a character class for digits. There are other character classes as well.
3737

38-
As mais usadas são:
38+
Most used are:
3939

40-
`padrão:\d` ("d" é de "digit")
41-
: Um dígito: um caractere de `0` a `9`.
40+
`pattern:\d` ("d" is from "digit")
41+
: A digit: a character from `0` to `9`.
4242

43-
`padrão:\s` ("s" é de "space")
44-
: Um símbolo de espaço: inclui espaços, tabulações `\t`, novas linhas `\n` e alguns outros caracteres raros, como `\v`, `\f` and `\r`.
43+
`pattern:\s` ("s" is from "space")
44+
: A space symbol: includes spaces, tabs `\t`, newlines `\n` and few other rare characters, such as `\v`, `\f` and `\r`.
4545

46-
`padrão:\w` ("w" é de "word")
47-
: Um caractere de texto: uma letra do alfabeto latino ou um dígito ou um sublinhado `_`. Letras não latinas (como cirílico ou hindu) não pertecem ao `padrão:\w`.
46+
`pattern:\w` ("w" is from "word")
47+
: A "wordly" character: either a letter of Latin alphabet or a digit or an underscore `_`. Non-Latin letters (like cyrillic or hindi) do not belong to `pattern:\w`.
4848

49-
Por exemplo, `padrão:\d\s\w` significa um "dígito" seguido de um "caractere de espaço" seguido de um "caractere de texto", como `correspondência:1 a`.
49+
For instance, `pattern:\d\s\w` means a "digit" followed by a "space character" followed by a "wordly character", such as `match:1 a`.
5050

51-
**Uma regexp pode conter símbolos regulares e classes de caracteres.**
51+
**A regexp may contain both regular symbols and character classes.**
5252

53-
Por exemplo, `padrão:CSS\d` corresponde a uma string `correspondência:CSS` com um dígito após:
53+
For instance, `pattern:CSS\d` matches a string `match:CSS` with a digit after it:
5454

5555
```js run
56-
let str = "Existe CSS4?";
56+
let str = "Is there CSS4?";
5757
let regexp = /CSS\d/
5858

5959
alert( str.match(regexp) ); // CSS4
6060
```
6161

62-
Também podemos usar muitas classes de caracteres:
62+
Also we can use many character classes:
6363

6464
```js run
65-
alert( "Eu amo HTML5!".match(/\s\w\w\w\w\d/) ); // ' HTML5'
65+
alert( "I love HTML5!".match(/\s\w\w\w\w\d/) ); // ' HTML5'
6666
```
6767

68-
A correspondência (cada classe de caracteres regexp possui o caractere de resultado correspondente):
68+
The match (each regexp character class has the corresponding result character):
6969

7070
![](love-html5-classes.svg)
7171

72-
## Classes inversas
72+
## Inverse classes
7373

74-
Para cada classe de caractere existe uma "classe inversa", denotada com a mesma letra, mas em maiúsculas.
74+
For every character class there exists an "inverse class", denoted with the same letter, but uppercased.
7575

76-
O "inverso" significa que ele corresponde a todos os outros caracteres, por exemplo:
76+
The "inverse" means that it matches all other characters, for instance:
7777

78-
`padrão:\D`
79-
: Sem dígito: qualquer caractere, exceto `padrão:\d`, por exemplo, uma letra.
78+
`pattern:\D`
79+
: Non-digit: any character except `pattern:\d`, for instance a letter.
8080

81-
`padrão:\S`
82-
: Sem espaço: qualquer caractere, exceto `padrão:\s`, por exemplo, uma letra.
81+
`pattern:\S`
82+
: Non-space: any character except `pattern:\s`, for instance a letter.
8383

84-
`padrão:\W`
85-
: Caractere não verbal: qualquer coisa, exceto `padrão:\w`, por exemploo uma letra não latina ou um espaço.
84+
`pattern:\W`
85+
: Non-wordly character: anything but `pattern:\w`, e.g a non-latin letter or a space.
8686

87-
No início do capítulo, vimos como criar um número de telefone somente para números a partir de uma string como `subject:+7(903)-123-45-67`: encontre todos os dígitos e junte-se a eles.
87+
In the beginning of the chapter we saw how to make a number-only phone number from a string like `subject:+7(903)-123-45-67`: find all digits and join them.
8888

8989
```js run
9090
let str = "+7(903)-123-45-67";
9191

9292
alert( str.match(/\d/g).join('') ); // 79031234567
9393
```
9494

95-
Uma maneira alternativa e mais curta é encontrar um `padrão:\D` não-dígito e removê-lo da string:
95+
An alternative, shorter way is to find non-digits `pattern:\D` and remove them from the string:
9696

9797
```js run
9898
let str = "+7(903)-123-45-67";
9999

100100
alert( str.replace(/\D/g, "") ); // 79031234567
101101
```
102102

103-
## Um ponto é "qualquer caractere"
103+
## A dot is "any character"
104104

105-
Um ponto `padrão:.` é uma classe de caractere especial que corresponde a "qualquer caractere, exceto uma nova linha".
105+
A dot `pattern:.` is a special character class that matches "any character except a newline".
106106

107-
Por exemplo:
107+
For instance:
108108

109109
```js run
110110
alert( "Z".match(/./) ); // Z
111111
```
112112

113-
Ou no meio de uma regexp:
113+
Or in the middle of a regexp:
114114

115115
```js run
116116
let regexp = /CS.4/;
117117

118118
alert( "CSS4".match(regexp) ); // CSS4
119119
alert( "CS-4".match(regexp) ); // CS-4
120-
alert( "CS 4".match(regexp) ); // CS 4 (o espaço é também um caractere)
120+
alert( "CS 4".match(regexp) ); // CS 4 (space is also a character)
121121
```
122122

123-
Observe que um ponto significa "qualquer caractere", mas não a "ausência de um caractere". Deve haver um caractere para corresponder a ele:
123+
Please note that a dot means "any character", but not the "absence of a character". There must be a character to match it:
124124

125125
```js run
126-
alert( "CS4".match(/CS.4/) ); // null, sem correspondência porque não há caractere para o ponto
126+
alert( "CS4".match(/CS.4/) ); // null, no match because there's no character for the dot
127127
```
128128

129-
### Ponto como literalmente qualquer caractere com a flag "s"
129+
### Dot as literally any character with "s" flag
130130

131-
Por padrão, um ponto não corresponde ao caractere de nova linha `\n`.
131+
By default, a dot doesn't match the newline character `\n`.
132132

133-
Por exemplo, a regexp `padrão:A.B` corresponde `corresponde:A` e, em seguida, `corresponde:B` com qualquer caractere entre eles, exceto uma nova linha `\n`:
133+
For instance, the regexp `pattern:A.B` matches `match:A`, and then `match:B` with any character between them, except a newline `\n`:
134134

135135
```js run
136-
alert( "A\nB".match(/A.B/) ); // null (sem correspondência)
136+
alert( "A\nB".match(/A.B/) ); // null (no match)
137137
```
138138

139-
Há muitas situações em que gostaríamos que um ponto significasse literalmente "qualquer caractere", incluindo a nova linha.
139+
There are many situations when we'd like a dot to mean literally "any character", newline included.
140140

141-
É o que flag `padrão:s` faz. Se uma regexp possui, então um ponto `padrão:.` corresponde literalmente a qualquer caractere:
141+
That's what flag `pattern:s` does. If a regexp has it, then a dot `pattern:.` matches literally any character:
142142

143143
```js run
144-
alert( "A\nB".match(/A.B/s) ); // A\nB (correspondência!)
144+
alert( "A\nB".match(/A.B/s) ); // A\nB (match!)
145145
```
146146

147-
````warn header="Não suportado no Firefox, IE, Edge"
148-
Verifique <https://caniuse.com/#search=dotall> para obter o estado de suporte mais recente. No momento da redação deste documento, não inclui o Firefox, IE, Edge.
147+
````warn header="Not supported in IE"
148+
The `pattern:s` flag is not supported in IE.
149149
150-
Felizmente, há uma alternativa, que funciona em qualquer lugar. Podemos usar uma regexp como `padrão:[\s\S]` para corresponder a "qualquer caractere".
150+
Luckily, there's an alternative, that works everywhere. We can use a regexp like `pattern:[\s\S]` to match "any character" (this pattern will be covered in the article <info:regexp-character-sets-and-ranges>).
151151
152152
```js run
153153
alert( "A\nB".match(/A[\s\S]B/) ); // A\nB (match!)
154154
```
155155
156-
O padrão `padrão:[\s\S]` diz literalmente: "um caractere de espaço OU não um caractere de espaço". Em outras palavras, "qualquer coisa". Poderíamos usar outro par de classes complementares, como `padrão:[\d\D]`, que não importa. Ou mesmo o padrão `padrão:[^]` - pois significa corresponder a qualquer caractere, exceto nada.
156+
The pattern `pattern:[\s\S]` literally says: "a space character OR not a space character". In other words, "anything". We could use another pair of complementary classes, such as `pattern:[\d\D]`, that doesn't matter. Or even the `pattern:[^]` -- as it means match any character except nothing.
157157
158-
Também podemos usar esse truque se quisermos os dois tipos de "pontos" no mesmo padrão: o ponto real `padrão:.` comportando-se da maneira regular ("não incluindo uma nova linha") e também uma maneira de combinar "qualquer caractere" com `padrão:[\s\S]` ou similar.
158+
Also we can use this trick if we want both kind of "dots" in the same pattern: the actual dot `pattern:.` behaving the regular way ("not including a newline"), and also a way to match "any character" with `pattern:[\s\S]` or alike.
159159
````
160160

161-
````warn header="Preste atenção nos espaços"
162-
Geralmente prestamos pouca atenção aos espaços. Para nós, as strings `sujeito:1-5` e `sujeito:1 - 5` são quase idênticas.
161+
````warn header="Pay attention to spaces"
162+
Usually we pay little attention to spaces. For us strings `subject:1-5` and `subject:1 - 5` are nearly identical.
163163
164-
Mas se uma regexp não leva em consideração os espaços, ela pode falhar.
164+
But if a regexp doesn't take spaces into account, it may fail to work.
165165
166-
Vamos tentar encontrar dígitos separados por um hífen:
166+
Let's try to find digits separated by a hyphen:
167167
168168
```js run
169-
alert( "1 - 5".match(/\d-\d/) ); // null, sem correspondência!
169+
alert( "1 - 5".match(/\d-\d/) ); // null, no match!
170170
```
171171
172-
Vamos corrigi-lo adicionando espaços ao padrão regexp `padrão:\d - \d`:
172+
Let's fix it adding spaces into the regexp `pattern:\d - \d`:
173173
174174
```js run
175-
alert( "1 - 5".match(/\d - \d/) ); // 1 - 5, agora funciona
176-
// ou podemos usar a classe \s:
177-
alert( "1 - 5".match(/\d\s-\s\d/) ); // 1 - 5, também funciona
175+
alert( "1 - 5".match(/\d - \d/) ); // 1 - 5, now it works
176+
// or we can use \s class:
177+
alert( "1 - 5".match(/\d\s-\s\d/) ); // 1 - 5, also works
178178
```
179179
180-
**Um espaço é um caractere. Igual em importância com qualquer outro caractere.**
180+
**A space is a character. Equal in importance with any other character.**
181181
182-
Não podemos adicionar ou remover espaços de uma expressão regular e esperamos funcionar da mesma maneira.
182+
We can't add or remove spaces from a regular expression and expect it to work the same.
183183
184-
Em outras palavras, em uma expressão regular, todos os caracteres são importantes, espaços também.
184+
In other words, in a regular expression all characters matter, spaces too.
185185
````
186186

187-
## Resumo
187+
## Summary
188188

189-
Existem as seguintes classes de caracteres:
189+
There exist following character classes:
190190

191-
- `padrão:\d` - dígitos.
192-
- `padrão:\D` - sem dígitos.
193-
- `padrão:\s` - símbolos de espaço, tabulações, novas linhas.
194-
- `padrão:\S` - todos, exceto `padrão:\s`.
195-
- `padrão:\w` - Letras latinas, dígitos, sublinhado `'_'`.
196-
- `padrão:\W` - todos, exceto `padrão:\w`.
197-
- `padrão:.` - qualquer caractere se estiver com a flag regexp `'s' `; caso contrário, qualquer um, exceto uma nova linha `\n`.
191+
- `pattern:\d` -- digits.
192+
- `pattern:\D` -- non-digits.
193+
- `pattern:\s` -- space symbols, tabs, newlines.
194+
- `pattern:\S` -- all but `pattern:\s`.
195+
- `pattern:\w` -- Latin letters, digits, underscore `'_'`.
196+
- `pattern:\W` -- all but `pattern:\w`.
197+
- `pattern:.` -- any character if with the regexp `'s'` flag, otherwise any except a newline `\n`.
198198

199-
...Mas isso não é tudo!
199+
...But that's not all!
200200

201-
A codificação unicode, usada pelo JavaScript para strings, fornece muitas propriedades para caracteres, como: a qual idioma a letra pertence (se é uma letra), é um sinal de pontuação etc.
201+
Unicode encoding, used by JavaScript for strings, provides many properties for characters, like: which language the letter belongs to (if it's a letter), is it a punctuation sign, etc.
202202

203-
Também podemos pesquisar por essas propriedades. Isso requer a flag `padrão:u`, abordada no próximo artigo.
203+
We can search by these properties as well. That requires flag `pattern:u`, covered in the next article.

0 commit comments

Comments
 (0)