|
1 |
| -# Sets and ranges [...] |
| 1 | +# Conjuntos y rangos [...] |
2 | 2 |
|
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". |
4 | 4 |
|
5 |
| -## Sets |
| 5 | +## Conjuntos |
6 | 6 |
|
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'`. |
8 | 8 |
|
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: |
10 | 10 |
|
11 | 11 | ```js run
|
12 |
| -// find [t or m], and then "op" |
| 12 | +// encontrar [t ó m], y luego "op" |
13 | 13 | alert( "Mop top".match(/[tm]op/gi) ); // "Mop", "top"
|
14 | 14 | ```
|
15 | 15 |
|
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. |
17 | 17 |
|
18 |
| -So the example below gives no matches: |
| 18 | +Entonces, en el siguiente ejemplo no hay coincidencias: |
19 | 19 |
|
20 | 20 | ```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 |
23 | 23 | ```
|
24 | 24 |
|
25 |
| -The pattern searches for: |
| 25 | +El patrón busca: |
26 | 26 |
|
27 | 27 | - `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`. |
30 | 30 |
|
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`. |
32 | 32 |
|
33 |
| -## Ranges |
| 33 | +## Rangos |
34 | 34 |
|
35 |
| -Square brackets may also contain *character ranges*. |
| 35 | +Los corchetes también pueden contener *rangos de caracteres*. |
36 | 36 |
|
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`. |
38 | 38 |
|
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`: |
40 | 40 |
|
41 | 41 | ```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 |
43 | 43 | ```
|
44 | 44 |
|
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`. |
46 | 46 |
|
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`. |
48 | 48 |
|
49 |
| -We can also use character classes inside `[…]`. |
| 49 | +También podemos usar clases de caracteres dentro de los `[…]`. |
50 | 50 |
|
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-]`. |
52 | 52 |
|
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". |
54 | 54 |
|
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: |
57 | 57 |
|
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. |
61 | 61 | ```
|
62 | 62 |
|
63 |
| -### Example: multi-language \w |
| 63 | +### Ejemplo: multi-idioma \w |
64 | 64 |
|
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. |
66 | 66 |
|
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}]`. |
68 | 68 |
|
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: |
70 | 70 |
|
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. |
76 | 76 |
|
77 |
| -An example of use: |
| 77 | +Un ejemplo de uso: |
78 | 78 |
|
79 | 79 | ```js run
|
80 | 80 | let regexp = /[\p{Alpha}\p{M}\p{Nd}\p{Pc}\p{Join_C}]/gu;
|
81 | 81 |
|
82 |
| -let str = `Hi 你好 12`; |
| 82 | +let str = `Hola 你好 12`; |
83 | 83 |
|
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 |
86 | 86 | ```
|
87 | 87 |
|
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>. |
89 | 89 |
|
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/). |
92 | 92 |
|
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. |
94 | 94 | ```
|
95 | 95 |
|
96 |
| -## Excluding ranges |
| 96 | +## Excluyendo rangos |
97 | 97 |
|
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:[^…]`. |
99 | 99 |
|
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*. |
101 | 101 |
|
102 |
| -For instance: |
| 102 | +Por ejemplo: |
103 | 103 |
|
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`. |
107 | 107 |
|
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: |
109 | 109 |
|
110 | 110 | ```js run
|
111 |
| -alert( "[email protected]". match( /[^\d\sA-Z]/gi) ); // @ and . |
| 111 | +alert( "[email protected]". match( /[^\d\sA-Z]/gi) ); // @ y . |
112 | 112 | ```
|
113 | 113 |
|
114 |
| -## Escaping in […] |
| 114 | +## Escapando dentro de corchetes […] |
115 | 115 |
|
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. |
117 | 117 |
|
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: |
119 | 119 |
|
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). |
124 | 124 |
|
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. |
126 | 126 |
|
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. |
128 | 128 |
|
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 `-().^+`: |
130 | 130 |
|
131 | 131 | ```js run
|
132 |
| -// No need to escape |
| 132 | +// no es necesario escaparlos |
133 | 133 | let regexp = /[-().^+]/g;
|
134 | 134 |
|
135 |
| -alert( "1 + 2 - 3".match(regexp) ); // Matches +, - |
| 135 | +alert( "1 + 2 - 3".match(regexp) ); // Coincide +, - |
136 | 136 | ```
|
137 | 137 |
|
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: |
139 | 139 |
|
140 | 140 | ```js run
|
141 |
| -// Escaped everything |
| 141 | +// Todo escapado |
142 | 142 | let regexp = /[\-\(\)\.\^\+]/g;
|
143 | 143 |
|
144 |
| -alert( "1 + 2 - 3".match(regexp) ); // also works: +, - |
| 144 | +alert( "1 + 2 - 3".match(regexp) ); // funciona también: +, - |
145 | 145 | ```
|
146 | 146 |
|
147 |
| -## Ranges and flag "u" |
| 147 | +## Rangos y la bandera (flag) "u" |
148 | 148 |
|
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. |
150 | 150 |
|
151 |
| -For instance, let's look for `pattern:[𝒳𝒴]` in the string `subject:𝒳`: |
| 151 | +Por ejemplo, busquemos `pattern:[𝒳𝒴]` en la cadena `subject:𝒳`: |
152 | 152 |
|
153 | 153 | ```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) |
156 | 156 | ```
|
157 | 157 |
|
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. |
159 | 159 |
|
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)`. |
165 | 165 |
|
166 |
| -We can see their codes like this: |
| 166 | +Sus códigos se pueden mostrar ejecutando: |
167 | 167 |
|
168 | 168 | ```js run
|
169 |
| -for(let i=0; i<'𝒳𝒴'.length; i++) { |
| 169 | +for(let i = 0; i < '𝒳𝒴'.length; i++) { |
170 | 170 | alert('𝒳𝒴'.charCodeAt(i)); // 55349, 56499, 55349, 56500
|
171 | 171 | };
|
172 | 172 | ```
|
173 | 173 |
|
174 |
| -So, the example above finds and shows the left half of `𝒳`. |
| 174 | +Entonces, el ejemplo anterior encuentra y muestra la mitad izquierda de `𝒳`. |
175 | 175 |
|
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: |
177 | 177 |
|
178 | 178 | ```js run
|
179 | 179 | alert( '𝒳'.match(/[𝒳𝒴]/u) ); // 𝒳
|
180 | 180 | ```
|
181 | 181 |
|
182 |
| -The similar situation occurs when looking for a range, such as `[𝒳-𝒴]`. |
| 182 | +Ocurre una situación similar cuando se busca un rango, como`[𝒳-𝒴]`. |
183 | 183 |
|
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: |
185 | 185 |
|
186 | 186 | ```js run
|
187 |
| -'𝒳'.match(/[𝒳-𝒴]/); // Error: Invalid regular expression |
| 187 | +'𝒳'.match(/[𝒳-𝒴]/); // Error: Expresión regular inválida |
188 | 188 | ```
|
189 | 189 |
|
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. |
191 | 191 |
|
192 |
| -With the flag `pattern:u` the pattern works correctly: |
| 192 | +Con la bandera `pattern:u` el patrón funciona correctamente: |
193 | 193 |
|
194 | 194 | ```js run
|
195 |
| -// look for characters from 𝒳 to 𝒵 |
| 195 | +// buscar caracteres desde 𝒳 a 𝒵 |
196 | 196 | alert( '𝒴'.match(/[𝒳-𝒵]/u) ); // 𝒴
|
197 | 197 | ```
|
0 commit comments