Skip to content

Commit e192dda

Browse files
authored
Merge pull request #296 from cortizg/es.javascript.info.9-08-sr
Sets and ranges [...]
2 parents bd8ad7a + 930a0df commit e192dda

File tree

5 files changed

+105
-105
lines changed

5 files changed

+105
-105
lines changed

9-regular-expressions/08-regexp-character-sets-and-ranges/1-find-range-1/solution.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
1-
Answers: **no, yes**.
1+
Respuestas: **no, si**.
22

3-
- In the script `subject:Java` it doesn't match anything, because `pattern:[^script]` means "any character except given ones". So the regexp looks for `"Java"` followed by one such symbol, but there's a string end, no symbols after it.
3+
- En el script `subject:Java` no coincide con nada, porque `pattern:[^script]` significa "cualquier carácter excepto los dados". Entonces, la expresión regular busca `"Java"` seguido de uno de esos símbolos, pero hay un final de cadena, sin símbolos posteriores.
44

55
```js run
66
alert( "Java".match(/Java[^script]/) ); // null
77
```
8-
- Yes, because the part `pattern:[^script]` part matches the character `"S"`. It's not one of `pattern:script`. As the regexp is case-sensitive (no `pattern:i` flag), it treats `"S"` as a different character from `"s"`.
8+
- Sí, porque la sección `pattern:[^script]` en parte coincide con el carácter `"S"`. No está en `pattern:script`. Como el regexp distingue entre mayúsculas y minúsculas (sin flag `pattern:i`), procesa a `"S"` como un carácter diferente de `"s"`.
99

1010
```js run
1111
alert( "JavaScript".match(/Java[^script]/) ); // "JavaS"
Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
# Java[^script]
22

3-
We have a regexp `pattern:/Java[^script]/`.
3+
Tenemos una regexp `pattern:/Java[^script]/`.
44

5-
Does it match anything in the string `subject:Java`? In the string `subject:JavaScript`?
5+
¿Coincide con algo en la cadena `subject:Java`? ¿Y en la cadena `subject:JavaScript`?
Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
1-
Answer: `pattern:\d\d[-:]\d\d`.
1+
Respuesta: `pattern:\d\d[-:]\d\d`.
22

33
```js run
44
let regexp = /\d\d[-:]\d\d/g;
5-
alert( "Breakfast at 09:00. Dinner at 21-30".match(regexp) ); // 09:00, 21-30
5+
alert( "El desayuno es a las 09:00. La cena es a las 21-30".match(regexp) ); // 09:00, 21-30
66
```
77

8-
Please note that the dash `pattern:'-'` has a special meaning in square brackets, but only between other characters, not when it's in the beginning or at the end, so we don't need to escape it.
8+
Tenga en cuenta que el guión `pattern:'-'` tiene un significado especial entre corchetes, pero solo entre otros caracteres, no al principio o al final, por lo que no necesitamos escaparlo.
Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
1-
# Find the time as hh:mm or hh-mm
1+
# Encuetra la hora como hh:mm o hh-mm
22

3-
The time can be in the format `hours:minutes` or `hours-minutes`. Both hours and minutes have 2 digits: `09:00` or `21-30`.
3+
La hora puede estar en el formato `horas:minutos` u `horas-minutos`. Tanto las horas como los minutos tienen 2 dígitos: `09:00` ó `21-30`.
44

5-
Write a regexp to find time:
5+
Escribe una regexp que encuentre la hora:
66

77
```js
8-
let regexp = /your regexp/g;
9-
alert( "Breakfast at 09:00. Dinner at 21-30".match(regexp) ); // 09:00, 21-30
8+
let regexp = /tu regexp/g;
9+
alert( "El desayuno es a las 09:00. La cena es a las 21-30".match(regexp) ); // 09:00, 21-30
1010
```
1111

12-
P.S. In this task we assume that the time is always correct, there's no need to filter out bad strings like "45:67". Later we'll deal with that too.
12+
En esta tarea asumimos que el tiempo siempre es correcto, no hay necesidad de filtrar cadenas malas como "45:67". Más tarde nos ocuparemos de eso también.
Lines changed: 91 additions & 91 deletions
Original file line numberDiff line numberDiff line change
@@ -1,197 +1,197 @@
1-
# Sets and ranges [...]
1+
# Conjuntos y rangos [...]
22

3-
Several characters or character classes inside square brackets `[…]` mean to "search for any character among given".
3+
Varios caracteres o clases de caracteres entre corchetes `[…]` significa "buscar cualquier carácter entre los dados".
44

5-
## Sets
5+
## Conjuntos
66

7-
For instance, `pattern:[eao]` means any of the 3 characters: `'a'`, `'e'`, or `'o'`.
7+
Por ejemplo, `pattern:[eao]` significa cualquiera de los 3 caracteres: `'a'`, `'e'`, o `'o'`.
88

9-
That's called a *set*. Sets can be used in a regexp along with regular characters:
9+
A esto se le llama *conjunto*. Los conjuntos se pueden usar en una expresión regular junto con los caracteres normales:
1010

1111
```js run
12-
// find [t or m], and then "op"
12+
// encontrar [t ó m], y luego "op"
1313
alert( "Mop top".match(/[tm]op/gi) ); // "Mop", "top"
1414
```
1515

16-
Please note that although there are multiple characters in the set, they correspond to exactly one character in the match.
16+
Tenga en cuenta que aunque hay varios caracteres en el conjunto, corresponden exactamente a un carácter en la coincidencia.
1717

18-
So the example below gives no matches:
18+
Entonces, en el siguiente ejemplo no hay coincidencias:
1919

2020
```js run
21-
// find "V", then [o or i], then "la"
22-
alert( "Voila".match(/V[oi]la/) ); // null, no matches
21+
// encuentra "V", luego [o ó i], luego "la"
22+
alert( "Voila".match(/V[oi]la/) ); // null, sin coincidencias
2323
```
2424

25-
The pattern searches for:
25+
El patrón busca:
2626

2727
- `pattern:V`,
28-
- then *one* of the letters `pattern:[oi]`,
29-
- then `pattern:la`.
28+
- después *una* de las letras `pattern:[oi]`,
29+
- después `pattern:la`.
3030

31-
So there would be a match for `match:Vola` or `match:Vila`.
31+
Entonces habría una coincidencia para `match:Vola` o `match:Vila`.
3232

33-
## Ranges
33+
## Rangos
3434

35-
Square brackets may also contain *character ranges*.
35+
Los corchetes también pueden contener *rangos de caracteres*.
3636

37-
For instance, `pattern:[a-z]` is a character in range from `a` to `z`, and `pattern:[0-5]` is a digit from `0` to `5`.
37+
Por ejemplo, `pattern:[a-z]` es un carácter en el rango de `a` a `z`, y `pattern:[0-5]` es un dígito de `0` a `5`.
3838

39-
In the example below we're searching for `"x"` followed by two digits or letters from `A` to `F`:
39+
En el ejemplo a continuación, estamos buscando `"x"` seguido de dos dígitos o letras de `A` a `F`:
4040

4141
```js run
42-
alert( "Exception 0xAF".match(/x[0-9A-F][0-9A-F]/g) ); // xAF
42+
alert( "Excepción 0xAF".match(/x[0-9A-F][0-9A-F]/g) ); // xAF
4343
```
4444

45-
Here `pattern:[0-9A-F]` has two ranges: it searches for a character that is either a digit from `0` to `9` or a letter from `A` to `F`.
45+
Aquí `pattern:[0-9A-F]` tiene dos rangos: busca un carácter que sea un dígito de `0` a `9` o una letra de `A` a `F`.
4646

47-
If we'd like to look for lowercase letters as well, we can add the range `a-f`: `pattern:[0-9A-Fa-f]`. Or add the flag `pattern:i`.
47+
Si también queremos buscar letras minúsculas, podemos agregar el rango `a-f`: `pattern:[0-9A-Fa-f]`. O se puede agregar la bandera `pattern:i`.
4848

49-
We can also use character classes inside `[…]`.
49+
También podemos usar clases de caracteres dentro de los `[…]`.
5050

51-
For instance, if we'd like to look for a wordly character `pattern:\w` or a hyphen `pattern:-`, then the set is `pattern:[\w-]`.
51+
Por ejemplo, si quisiéramos buscar un carácter de palabra `pattern:\w` o un guión `pattern:-`, entonces el conjunto es `pattern:[\w-]`.
5252

53-
Combining multiple classes is also possible, e.g. `pattern:[\s\d]` means "a space character or a digit".
53+
También es posible combinar varias clases, p.ej.: `pattern:[\s\d]` significa "un carácter de espacio o un dígito".
5454

55-
```smart header="Character classes are shorthands for certain character sets"
56-
For instance:
55+
```smart header="Las clases de caracteres son abreviaturas (o atajos) para ciertos conjuntos de caracteres."
56+
Por ejemplo:
5757
58-
- **\d** -- is the same as `pattern:[0-9]`,
59-
- **\w** -- is the same as `pattern:[a-zA-Z0-9_]`,
60-
- **\s** -- is the same as `pattern:[\t\n\v\f\r ]`, plus few other rare unicode space characters.
58+
- **\d** -- es lo mismo que `pattern:[0-9]`,
59+
- **\w** -- es lo mismo que `pattern:[a-zA-Z0-9_]`,
60+
- **\s** -- es lo mismo que `pattern:[\t\n\v\f\r ]`, además de otros caracteres de espacio raros de unicode.
6161
```
6262

63-
### Example: multi-language \w
63+
### Ejemplo: multi-idioma \w
6464

65-
As the character class `pattern:\w` is a shorthand for `pattern:[a-zA-Z0-9_]`, it can't find Chinese hieroglyphs, Cyrillic letters, etc.
65+
Como la clase de caracteres `pattern:\w` es una abreviatura de `pattern:[a-zA-Z0-9_]`, no puede coincidir con sinogramas chinos, letras cirílicas, etc.
6666

67-
We can write a more universal pattern, that looks for wordly characters in any language. That's easy with unicode properties: `pattern:[\p{Alpha}\p{M}\p{Nd}\p{Pc}\p{Join_C}]`.
67+
Podemos escribir un patrón más universal, que busque caracteres de palabra en cualquier idioma. Eso es fácil con las propiedades unicode: `pattern:[\p{Alpha}\p{M}\p{Nd}\p{Pc}\p{Join_C}]`.
6868

69-
Let's decipher it. Similar to `pattern:\w`, we're making a set of our own that includes characters with following unicode properties:
69+
Descifrémoslo. Similar a `pattern:\w`, estamos creando un conjunto propio que incluye caracteres con las siguientes propiedades unicode:
7070

71-
- `Alphabetic` (`Alpha`) - for letters,
72-
- `Mark` (`M`) - for accents,
73-
- `Decimal_Number` (`Nd`) - for digits,
74-
- `Connector_Punctuation` (`Pc`) - for the underscore `'_'` and similar characters,
75-
- `Join_Control` (`Join_C`) - two special codes `200c` and `200d`, used in ligatures, e.g. in Arabic.
71+
- `Alfabético` (`Alpha`) - para letras,
72+
- `Marca` (`M`) - para acentos,
73+
- `Numero_Decimal` (`Nd`) - para dígitos,
74+
- `Conector_Puntuación` (`Pc`) - para guión bajo `'_'` y caracteres similares,
75+
- `Control_Unión` (`Join_C`) - dos códigos especiales `200c` and `200d`, utilizado en ligaduras, p.ej. en árabe.
7676

77-
An example of use:
77+
Un ejemplo de uso:
7878

7979
```js run
8080
let regexp = /[\p{Alpha}\p{M}\p{Nd}\p{Pc}\p{Join_C}]/gu;
8181

82-
let str = `Hi 你好 12`;
82+
let str = `Hola 你好 12`;
8383

84-
// finds all letters and digits:
85-
alert( str.match(regexp) ); // H,i,你,好,1,2
84+
// encuentra todas las letras y dígitos:
85+
alert( str.match(regexp) ); // H,o,l,a,你,好,1,2
8686
```
8787

88-
Of course, we can edit this pattern: add unicode properties or remove them. Unicode properties are covered in more details in the article <info:regexp-unicode>.
88+
Por supuesto, podemos editar este patrón: agregar propiedades unicode o eliminarlas. Las propiedades Unicode se cubren con más detalle en el artículo <info:regexp-unicode>.
8989

90-
```warn header="Unicode properties aren't supported in Edge and Firefox"
91-
Unicode properties `pattern:p{…}` are not yet implemented in Edge and Firefox. If we really need them, we can use library [XRegExp](http://xregexp.com/).
90+
```warn header="Las propiedades Unicode no son compatibles con Edge y Firefox"
91+
Las propiedades Unicode `pattern:p{…}` aún no se implementan en Edge y Firefox. Si realmente los necesitamos, podemos usar la biblioteca [XRegExp](http://xregexp.com/).
9292
93-
Or just use ranges of characters in a language that interests us, e.g. `pattern:[а-я]` for Cyrillic letters.
93+
O simplemente usa rangos de caracteres en el idioma de tu interés, p.ej. `pattern:[а-я]` para letras cirílicas.
9494
```
9595

96-
## Excluding ranges
96+
## Excluyendo rangos
9797

98-
Besides normal ranges, there are "excluding" ranges that look like `pattern:[^…]`.
98+
Además de los rangos normales, hay rangos "excluyentes" que se parecen a `pattern:[^…]`.
9999

100-
They are denoted by a caret character `^` at the start and match any character *except the given ones*.
100+
Están denotados por un carácter caret `^` al inicio y coinciden con cualquier carácter *excepto los dados*.
101101

102-
For instance:
102+
Por ejemplo:
103103

104-
- `pattern:[^aeyo]` -- any character except `'a'`, `'e'`, `'y'` or `'o'`.
105-
- `pattern:[^0-9]` -- any character except a digit, the same as `pattern:\D`.
106-
- `pattern:[^\s]` -- any non-space character, same as `\S`.
104+
- `pattern:[^aeyo]` -- cualquier carácter excepto `'a'`, `'e'`, `'y'` u `'o'`.
105+
- `pattern:[^0-9]` -- cualquier carácter excepto un dígito, igual que `pattern:\D`.
106+
- `pattern:[^\s]` -- cualquiere carácter sin espacio, igual que `\S`.
107107

108-
The example below looks for any characters except letters, digits and spaces:
108+
El siguiente ejemplo busca cualquier carácter, excepto letras, dígitos y espacios:
109109

110110
```js run
111-
alert( "[email protected]".match(/[^\d\sA-Z]/gi) ); // @ and .
111+
alert( "[email protected]".match(/[^\d\sA-Z]/gi) ); // @ y .
112112
```
113113

114-
## Escaping in []
114+
## Escapando dentro de corchetes []
115115

116-
Usually when we want to find exactly a special character, we need to escape it like `pattern:\.`. And if we need a backslash, then we use `pattern:\\`, and so on.
116+
Por lo general, cuando queremos encontrar exactamente un carácter especial, necesitamos escaparlo con `pattern:\.`. Y si necesitamos una barra invertida, entonces usamos `pattern:\\`, y así sucesivamente.
117117

118-
In square brackets we can use the vast majority of special characters without escaping:
118+
Entre corchetes podemos usar la gran mayoría de caracteres especiales sin escaparlos:
119119

120-
- Symbols `pattern:. + ( )` never need escaping.
121-
- A hyphen `pattern:-` is not escaped in the beginning or the end (where it does not define a range).
122-
- A caret `pattern:^` is only escaped in the beginning (where it means exclusion).
123-
- The closing square bracket `pattern:]` is always escaped (if we need to look for that symbol).
120+
- Los símbolos `pattern:. + ( )` nunca necesitan escape.
121+
- Un guión `pattern:-` no se escapa al principio ni al final (donde no define un rango).
122+
- Un carácter caret `pattern:^` solo se escapa al principio (donde significa exclusión).
123+
- El corchete de cierre `pattern:]` siempre se escapa (si se necesita buscarlo).
124124

125-
In other words, all special characters are allowed without escaping, except when they mean something for square brackets.
125+
En otras palabras, todos los caracteres especiales están permitidos sin escapar, excepto cuando significan algo entre corchetes.
126126

127-
A dot `.` inside square brackets means just a dot. The pattern `pattern:[.,]` would look for one of characters: either a dot or a comma.
127+
Un punto `.` dentro de corchetes significa solo un punto. El patrón `pattern:[.,]` Buscaría uno de los caracteres: un punto o una coma.
128128

129-
In the example below the regexp `pattern:[-().^+]` looks for one of the characters `-().^+`:
129+
En el siguiente ejemplo, la expresión regular `pattern: [-().^+]` busca uno de los caracteres `-().^+`:
130130

131131
```js run
132-
// No need to escape
132+
// no es necesario escaparlos
133133
let regexp = /[-().^+]/g;
134134

135-
alert( "1 + 2 - 3".match(regexp) ); // Matches +, -
135+
alert( "1 + 2 - 3".match(regexp) ); // Coincide +, -
136136
```
137137

138-
...But if you decide to escape them "just in case", then there would be no harm:
138+
...Pero si decides escaparlos "por si acaso", no habría daño:
139139

140140
```js run
141-
// Escaped everything
141+
// Todo escapado
142142
let regexp = /[\-\(\)\.\^\+]/g;
143143

144-
alert( "1 + 2 - 3".match(regexp) ); // also works: +, -
144+
alert( "1 + 2 - 3".match(regexp) ); // funciona también: +, -
145145
```
146146

147-
## Ranges and flag "u"
147+
## Rangos y la bandera (flag) "u"
148148

149-
If there are surrogate pairs in the set, flag `pattern:u` is required for them to work correctly.
149+
Si hay pares sustitutos en el conjunto, se requiere la flag `pattern:u` para que funcionen correctamente.
150150

151-
For instance, let's look for `pattern:[𝒳𝒴]` in the string `subject:𝒳`:
151+
Por ejemplo, busquemos `pattern:[𝒳𝒴]` en la cadena `subject:𝒳`:
152152

153153
```js run
154-
alert( '𝒳'.match(/[𝒳𝒴]/) ); // shows a strange character, like [?]
155-
// (the search was performed incorrectly, half-character returned)
154+
alert( '𝒳'.match(/[𝒳𝒴]/) ); // muestra un carácter extraño, como [?]
155+
// (la búsqueda se realizó incorrectamente, se devolvió medio carácter)
156156
```
157157

158-
The result is incorrect, because by default regular expressions "don't know" about surrogate pairs.
158+
El resultado es incorrecto porque, por defecto, las expresiones regulares "no saben" sobre pares sustitutos.
159159

160-
The regular expression engine thinks that `[𝒳𝒴]` -- are not two, but four characters:
161-
1. left half of `𝒳` `(1)`,
162-
2. right half of `𝒳` `(2)`,
163-
3. left half of `𝒴` `(3)`,
164-
4. right half of `𝒴` `(4)`.
160+
El motor de expresión regular piensa que la cadena `[𝒳𝒴]` no son dos, sino cuatro carácteres:
161+
1. mitad izquierda de `𝒳` `(1)`,
162+
2. mitad derecha de `𝒳` `(2)`,
163+
3. mitad izquierda de `𝒴` `(3)`,
164+
4. mitad derecha de `𝒴` `(4)`.
165165

166-
We can see their codes like this:
166+
Sus códigos se pueden mostrar ejecutando:
167167

168168
```js run
169-
for(let i=0; i<'𝒳𝒴'.length; i++) {
169+
for(let i = 0; i < '𝒳𝒴'.length; i++) {
170170
alert('𝒳𝒴'.charCodeAt(i)); // 55349, 56499, 55349, 56500
171171
};
172172
```
173173

174-
So, the example above finds and shows the left half of `𝒳`.
174+
Entonces, el ejemplo anterior encuentra y muestra la mitad izquierda de `𝒳`.
175175

176-
If we add flag `pattern:u`, then the behavior will be correct:
176+
Si agregamos la flag `pattern:u`, entonces el comportamiento será correcto:
177177

178178
```js run
179179
alert( '𝒳'.match(/[𝒳𝒴]/u) ); // 𝒳
180180
```
181181

182-
The similar situation occurs when looking for a range, such as `[𝒳-𝒴]`.
182+
Ocurre una situación similar cuando se busca un rango, como`[𝒳-𝒴]`.
183183

184-
If we forget to add flag `pattern:u`, there will be an error:
184+
Si olvidamos agregar la flag `pattern:u`, habrá un error:
185185

186186
```js run
187-
'𝒳'.match(/[𝒳-𝒴]/); // Error: Invalid regular expression
187+
'𝒳'.match(/[𝒳-𝒴]/); // Error: Expresión regular inválida
188188
```
189189

190-
The reason is that without flag `pattern:u` surrogate pairs are perceived as two characters, so `[𝒳-𝒴]` is interpreted as `[<55349><56499>-<55349><56500>]` (every surrogate pair is replaced with its codes). Now it's easy to see that the range `56499-55349` is invalid: its starting code `56499` is greater than the end `55349`. That's the formal reason for the error.
190+
La razón es que sin la bandera `pattern:u` los pares sustitutos se perciben como dos caracteres, por lo que `[𝒳-𝒴]` se interpreta como `[<55349><56499>-<55349><56500>]` (cada par sustituto se reemplaza con sus códigos). Ahora es fácil ver que el rango `56499-55349` es inválido: su código de inicio `56499` es mayor que el último `55349`. Esa es la razón formal del error.
191191

192-
With the flag `pattern:u` the pattern works correctly:
192+
Con la bandera `pattern:u` el patrón funciona correctamente:
193193

194194
```js run
195-
// look for characters from 𝒳 to 𝒵
195+
// buscar caracteres desde 𝒳 a 𝒵
196196
alert( '𝒴'.match(/[𝒳-𝒵]/u) ); // 𝒴
197197
```

0 commit comments

Comments
 (0)