Skip to content

Commit 2ab6399

Browse files
authored
Merge pull request #265 from cortizg/es.javascript.info.9-02-cc
Character classes
2 parents d950fad + 20f8905 commit 2ab6399

File tree

1 file changed

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

1 file changed

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

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`.
3+
Considera una tarea práctica: tenemos un número de teléfono como `"+7(903)-123-45-67"`, y debemos convertirlo en número puro: `79031234567`.
44

5-
To do so, we can find and remove anything that's not a number. Character classes can help with that.
5+
Para hacerlo, podemos encontrar y eliminar cualquier cosa que no sea un número. La clase de caracteres pueden ayudar con eso.
66

7-
A *character class* is a special notation that matches any symbol from a certain set.
7+
Una *clase de caracteres* es una notación especial que coincide con cualquier símbolo de un determinado conjunto.
88

9-
For the start, let's explore the "digit" class. It's written as `pattern:\d` and corresponds to "any single digit".
9+
Para empezar, exploremos la clase "dígito". Está escrito como `pattern:\d` y corresponde a "cualquier dígito".
1010

11-
For instance, the let's find the first digit in the phone number:
11+
Por ejemplo, busquemos el primer dígito en el número de teléfono:
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-
Without the flag `pattern:g`, the regular expression only looks for the first match, that is the first digit `pattern:\d`.
21+
Sin la bandera (flag) `pattern:g`, la expresión regular solo busca la primera coincidencia, es decir, el primer dígito `pattern:\d`.
2222

23-
Let's add the `pattern:g` flag to find all digits:
23+
Agreguemos la bandera `pattern:g` para encontrar todos los dígitos:
2424

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

2828
let regexp = /\d/g;
2929

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

32-
// let's make the digits-only phone number of them:
32+
// hagamos el número de teléfono de solo dígitos:
3333
alert( str.match(regexp).join('') ); // 79031234567
3434
```
3535

36-
That was a character class for digits. There are other character classes as well.
36+
Esa fue una clase de caracteres para los dígitos. También hay otras.
3737

38-
Most used are:
38+
Las más usadas son:
3939

40-
`pattern:\d` ("d" is from "digit")
41-
: A digit: a character from `0` to `9`.
40+
`pattern:\d` ("d" es de dígito")
41+
: Un dígito: es un caracter de `0` a `9`.
4242

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`.
43+
`pattern:\s` ("s" es un espacio)
44+
: Un símbolo de espacio: incluye espacios, tabulaciones `\t`, líneas nuevas `\n` y algunos otros caracteres raros, como `\v`, `\f` y `\r`.
4545

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`.
46+
`pattern:\w` ("w" es carácter de palabra)
47+
: Un carácter de palabra es: una letra del alfabeto latino o un dígito o un guión bajo `_`. Las letras no latinas (como el cirílico o el hindi) no pertenecen al `pattern:\w`.
4848

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`.
49+
Por ejemplo, `pattern:\d\s\w` significa un "dígito" seguido de un "carácter de espacio" seguido de un "carácter de palabra", como `match:1 a`.
5050

51-
**A regexp may contain both regular symbols and character classes.**
51+
**Una expresión regular puede contener símbolos regulares y clases de caracteres.**
5252

53-
For instance, `pattern:CSS\d` matches a string `match:CSS` with a digit after it:
53+
Por ejemplo, `pattern:CSS\d` coincide con una cadena `match:CSS` con un dígito después:
5454

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

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

62-
Also we can use many character classes:
62+
También podemos usar varias clases de caracteres:
6363

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

68-
The match (each regexp character class has the corresponding result character):
68+
La coincidencia (cada clase de carácter de la expresión regular tiene el carácter resultante correspondiente):
6969

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

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

74-
For every character class there exists an "inverse class", denoted with the same letter, but uppercased.
74+
Para cada clase de caracteres existe una "clase inversa", denotada con la misma letra, pero en mayúscula.
7575

76-
The "inverse" means that it matches all other characters, for instance:
76+
El "inverso" significa que coincide con todos los demás caracteres, por ejemplo:
7777

7878
`pattern:\D`
79-
: Non-digit: any character except `pattern:\d`, for instance a letter.
79+
: Sin dígitos: cualquier carácter excepto `pattern:\d`, por ejemplo, una letra.
8080

8181
`pattern:\S`
82-
: Non-space: any character except `pattern:\s`, for instance a letter.
82+
: Sin espacio: cualquier carácter excepto `pattern:\s`, por ejemplo, una letra.
8383

8484
`pattern:\W`
85-
: Non-wordly character: anything but `pattern:\w`, e.g a non-latin letter or a space.
85+
: Sin carácter de palabra: cualquier cosa menos `pattern:\w`, por ejemplo, una letra no latina o un espacio.
8686

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.
87+
Al comienzo del capítulo vimos cómo hacer un número de teléfono solo de números a partir de una cadena como `subject:+7(903)-123-45-67`: encontrar todos los dígitos y unirlos.
8888

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

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

95-
An alternative, shorter way is to find non-digits `pattern:\D` and remove them from the string:
95+
Una forma alternativa y más corta es usar el patrón sin dígito `pattern:\D` para encontrarlos y eliminarlos de la cadena:
9696

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

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

103-
## A dot is "any character"
103+
## Un punto es "cualquier carácter"
104104

105-
A dot `pattern:.` is a special character class that matches "any character except a newline".
105+
El patrón punto (`pattern:.`) es una clase de caracteres especial que coincide con "cualquier carácter excepto una nueva línea".
106106

107-
For instance:
107+
Por ejemplo:
108108

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

113-
Or in the middle of a regexp:
113+
O en medio de una expresión regular:
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 (space is also a character)
120+
alert( "CS 4".match(regexp) ); // CS 4 (el espacio también es un carácter)
121121
```
122122

123-
Please note that a dot means "any character", but not the "absense of a character". There must be a character to match it:
123+
Tenga en cuenta que un punto significa "cualquier carácter", pero no la "ausencia de un carácter". Debe haber un carácter para que coincida:
124124

125125
```js run
126-
alert( "CS4".match(/CS.4/) ); // null, no match because there's no character for the dot
126+
alert( "CS4".match(/CS.4/) ); // null, no coincide porque no hay caracteres entre S y 4
127127
```
128128

129-
### Dot as literally any character with "s" flag
129+
### Punto es igual a la bandera "s" que literalmente retorna cualquier carácter
130130

131-
By default, a dot doesn't match the newline character `\n`.
131+
Por defecto, *punto* no coincide con el carácter de línea nueva `\n`.
132132

133-
For instance, the regexp `pattern:A.B` matches `match:A`, and then `match:B` with any character between them, except a newline `\n`:
133+
Por ejemplo, la expresión regular `pattern:A.B` coincide con `match:A`, y luego `match:B` con cualquier carácter entre ellos, excepto una línea nueva `\n`:
134134

135135
```js run
136-
alert( "A\nB".match(/A.B/) ); // null (no match)
136+
alert( "A\nB".match(/A.B/) ); // null (sin coincidencia)
137137
```
138138

139-
There are many situations when we'd like a dot to mean literally "any character", newline included.
139+
Hay muchas situaciones en las que nos gustaría que *punto* signifique literalmente "cualquier carácter", incluida la línea nueva.
140140

141-
That's what flag `pattern:s` does. If a regexp has it, then a dot `pattern:.` matches literally any character:
141+
Eso es lo que hace la bandera `pattern:s`. Si una expresión regular la tiene, entonces `pattern:.` coincide literalmente con cualquier carácter:
142142

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

147-
````warn header="Not supported in Firefox, IE, Edge"
148-
Check <https://caniuse.com/#search=dotall> for the most recent state of support. At the time of writing it doesn't include Firefox, IE, Edge.
147+
````warn header="El patrón (`pattern:.`) no es compatible con Firefox (< 78), IE, Edge (< 79)"
148+
Consulte <https://caniuse.com/#search=dotall> para conocer el soporte actualizado. Al momento de escribirse este manual, no estaban soportados.
149149

150-
Luckily, there's an alternative, that works everywhere. We can use a regexp like `pattern:[\s\S]` to match "any character".
150+
Afortunadamente, hay una alternativa, que funciona en todas partes. Podemos usar una expresión regular como `pattern:[\s\S]` para que coincida con "cualquier carácter".
151151

152152
```js run
153-
alert( "A\nB".match(/A[\s\S]B/) ); // A\nB (match!)
153+
alert( "A\nB".match(/A[\s\S]B/) ); // A\nB (coincide!)
154154
```
155155

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.
156+
El patrón `pattern:[\s\S]` literalmente dice: "con carácter de espacio O sin carácter de espacio". En otras palabras, "cualquier cosa". Podríamos usar otro par de clases complementarias, como `pattern:[\d\D]`, eso no importa. O incluso `pattern:[^]`, que significa que coincide con cualquier carácter excepto nada.
157157

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.
158+
También podemos usar este truco si queremos ambos tipos de "puntos" en el mismo patrón: el patrón actual `pattern:.` comportándose de la manera regular ("sin incluir una línea nueva"), y la forma de hacer coincidir "cualquier carácter" con el patrón `pattern:[\s\S]` o similar.
159159
````
160160
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.
161+
````warn header="Presta atención a los espacios"
162+
Por lo general, prestamos poca atención a los espacios. Para nosotros, las cadenas `subject:1-5` y `subject:1 - 5` son casi idénticas.
163163
164-
But if a regexp doesn't take spaces into account, it may fail to work.
164+
Pero si una expresión regular no tiene en cuenta los espacios, puede que no funcione.
165165
166-
Let's try to find digits separated by a hyphen:
166+
Intentemos encontrar dígitos separados por un guión:
167167
168168
```js run
169-
alert( "1 - 5".match(/\d-\d/) ); // null, no match!
169+
alert( "1 - 5".match(/\d-\d/) ); // null, sin coincidencia!
170170
```
171171
172-
Let's fix it adding spaces into the regexp `pattern:\d - \d`:
172+
Vamos a arreglarlo agregando espacios en la expresión regular `pattern:\d - \d`:
173173
174174
```js run
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
175+
alert( "1 - 5".match(/\d - \d/) ); // 1 - 5, funciona ahora
176+
// o podemos usar la clase \s:
177+
alert( "1 - 5".match(/\d\s-\s\d/) ); // 1 - 5, tambien funciona
178178
```
179179
180-
**A space is a character. Equal in importance with any other character.**
180+
**Un espacio es un carácter. Igual de importante que cualquier otro carácter.**
181181
182-
We can't add or remove spaces from a regular expression and expect to work the same.
182+
No podemos agregar o eliminar espacios de una expresión regular y esperar que funcione igual.
183183
184-
In other words, in a regular expression all characters matter, spaces too.
184+
En otras palabras, en una expresión regular todos los caracteres importan, los espacios también.
185185
````
186186

187-
## Summary
187+
## Resumen
188188

189-
There exist following character classes:
189+
Existen las siguientes clases de caracteres:
190190

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`.
191+
- `pattern:\d` -- dígitos.
192+
- `pattern:\D` -- sin dígitos.
193+
- `pattern:\s` -- símbolos de espacio, tabulaciones, líneas nuevas.
194+
- `pattern:\S` -- todo menos `pattern:\s`.
195+
- `pattern:\w` -- letras latinas, dígitos, guión bajo `'_'`.
196+
- `pattern:\W` -- todo menos `pattern:\w`.
197+
- `pattern:.` -- cualquier caracter, si la expresión regular usa la bandera `'s'`, de otra forma cualquiera excepto **línea nueva** `\n`.
198198

199-
...But that's not all!
199+
...¡Pero eso no es todo!
200200

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) it is it a punctuation sign, etc.
201+
La codificación Unicode, utilizada por JavaScript para las cadenas, proporciona muchas propiedades para los caracteres, como: a qué idioma pertenece la letra (si es una letra), es un signo de puntuación, etc.
202202

203-
We can search by these properties as well. That requires flag `pattern:u`, covered in the next article.
203+
Se pueden hacer búsquedas usando esas propiedades. Y se requiere la bandera `pattern:u`, analizada en el siguiente artículo.

0 commit comments

Comments
 (0)