Skip to content

Commit da86cb5

Browse files
authored
Merge pull request #297 from cortizg/es.javascript.info.9-09-q
Quantifiers +, *, ? and {n}
2 parents e192dda + 8590abb commit da86cb5

File tree

5 files changed

+70
-70
lines changed

5 files changed

+70
-70
lines changed
Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11

2-
Solution:
2+
Solución:
33

44
```js run
55
let regexp = /\.{3,}/g;
6-
alert( "Hello!... How goes?.....".match(regexp) ); // ..., .....
6+
alert( "Hola!... ¿Cómo vas?.....".match(regexp) ); // ..., .....
77
```
88

9-
Please note that the dot is a special character, so we have to escape it and insert as `\.`.
9+
Tenga en cuenta que el punto es un carácter especial, por lo que debemos escaparlo e insertarlo como `\.`.

9-regular-expressions/09-regexp-quantifiers/1-find-text-manydots/task.md

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,13 @@ importance: 5
22

33
---
44

5-
# How to find an ellipsis "..." ?
5+
# ¿Cómo encontrar puntos suspensivos "..."?
66

7-
Create a regexp to find ellipsis: 3 (or more?) dots in a row.
7+
Escriba una regexp para encontrar puntos suspensivos: 3 (¿o más?) puntos en una fila.
88

9-
Check it:
9+
Revísalo:
1010

1111
```js
12-
let regexp = /your regexp/g;
13-
alert( "Hello!... How goes?.....".match(regexp) ); // ..., .....
12+
let regexp = /tu regexp/g;
13+
alert( "Hola!... ¿Cómo vas?.....".match(regexp) ); // ..., .....
1414
```
Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
1-
We need to look for `#` followed by 6 hexadecimal characters.
1+
Necesitamos buscar `#` seguido de 6 caracteres hexadecimales.
22

3-
A hexadecimal character can be described as `pattern:[0-9a-fA-F]`. Or if we use the `pattern:i` flag, then just `pattern:[0-9a-f]`.
3+
Un carácter hexadecimal se puede describir como `pattern:[0-9a-fA-F]`. O si usamos la bandera `pattern:i`, entonces simplemente `pattern:[0-9a-f]`.
44

5-
Then we can look for 6 of them using the quantifier `pattern:{6}`.
5+
Entonces podemos buscar 6 de ellos usando el cuantificador `pattern:{6}`.
66

7-
As a result, we have the regexp: `pattern:/#[a-f0-9]{6}/gi`.
7+
Como resultado, tenemos la regexp: `pattern:/#[a-f0-9]{6}/gi`.
88

99
```js run
1010
let regexp = /#[a-f0-9]{6}/gi;
@@ -14,18 +14,18 @@ let str = "color:#121212; background-color:#AA00ef bad-colors:f#fddee #fd2"
1414
alert( str.match(regexp) ); // #121212,#AA00ef
1515
```
1616

17-
The problem is that it finds the color in longer sequences:
17+
El problema es que también encuentra el color en secuencias más largas:
1818

1919
```js run
2020
alert( "#12345678".match( /#[a-f0-9]{6}/gi ) ) // #123456
2121
```
2222

23-
To fix that, we can add `pattern:\b` to the end:
23+
Para corregir eso, agregamos `pattern:\b` al final:
2424

2525
```js run
2626
// color
2727
alert( "#123456".match( /#[a-f0-9]{6}\b/gi ) ); // #123456
2828

29-
// not a color
29+
// sin color
3030
alert( "#12345678".match( /#[a-f0-9]{6}\b/gi ) ); // null
3131
```
Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,15 @@
1-
# Regexp for HTML colors
1+
# Regexp para colores HTML
22

3-
Create a regexp to search HTML-colors written as `#ABCDEF`: first `#` and then 6 hexadecimal characters.
3+
Escribe una regexp para encontrar colores HTML escritos como `#ABCDEF`: primero `#` y luego 6 caracteres hexadecimales.
44

5-
An example of use:
5+
Un ejemplo de uso:
66

77
```js
8-
let regexp = /...your regexp.../
8+
let regexp = /...tu regexp.../
99

1010
let str = "color:#121212; background-color:#AA00ef bad-colors:f#fddee #fd2 #12345678";
1111

1212
alert( str.match(regexp) ) // #121212,#AA00ef
1313
```
1414

15-
P.S. In this task we do not need other color formats like `#123` or `rgb(1,2,3)` etc.
15+
P.D. En esta tarea no necesitamos otro formato de color como `#123` o `rgb(1,2,3)`, etc.
Lines changed: 50 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -1,46 +1,46 @@
1-
# Quantifiers +, *, ? and {n}
1+
# Cuantificadores +, *, ? y {n}
22

3-
Let's say we have a string like `+7(903)-123-45-67` and want to find all numbers in it. But unlike before, we are interested not in single digits, but full numbers: `7, 903, 123, 45, 67`.
3+
Digamos que tenemos una cadena como `+7 (903) -123-45-67` y queremos encontrar todos los números en ella. Pero contrastando el ejemplo anterior, no estamos interesados en un solo dígito, sino en números completos: `7, 903, 123, 45, 67`.
44

5-
A number is a sequence of 1 or more digits `pattern:\d`. To mark how many we need, we can append a *quantifier*.
5+
Un número es una secuencia de 1 o más dígitos `pattern:\d`. Para marcar cuántos necesitamos, podemos agregar un *cuantificador*.
66

7-
## Quantity {n}
7+
## Cantidad {n}
88

9-
The simplest quantifier is a number in curly braces: `pattern:{n}`.
9+
El cuantificador más simple es un número entre llaves: `pattern:{n}`.
1010

11-
A quantifier is appended to a character (or a character class, or a `[...]` set etc) and specifies how many we need.
11+
Se agrega un cuantificador a un carácter (o a una clase de caracteres, o a un conjunto `[...]`, etc) y especifica cuántos necesitamos.
1212

13-
It has a few advanced forms, let's see examples:
13+
Tiene algunas formas avanzadas, veamos los ejemplos:
1414

15-
The exact count: `pattern:{5}`
16-
: `pattern:\d{5}` denotes exactly 5 digits, the same as `pattern:\d\d\d\d\d`.
15+
El recuento exacto: `pattern:{5}`
16+
: `pattern:\d{5}` Denota exactamente 5 dígitos, igual que `pattern:\d\d\d\d\d`.
1717

18-
The example below looks for a 5-digit number:
18+
El siguiente ejemplo busca un número de 5 dígitos:
1919

2020
```js run
21-
alert( "I'm 12345 years old".match(/\d{5}/) ); // "12345"
21+
alert( "Tengo 12345 años de edad".match(/\d{5}/) ); // "12345"
2222
```
2323

24-
We can add `\b` to exclude longer numbers: `pattern:\b\d{5}\b`.
24+
Podemos agregar `\b` para excluir números largos: `pattern:\b\d{5}\b`.
2525

26-
The range: `pattern:{3,5}`, match 3-5 times
27-
: To find numbers from 3 to 5 digits we can put the limits into curly braces: `pattern:\d{3,5}`
26+
El rango: `pattern:{3,5}`, coincide 3-5 veces
27+
: Para encontrar números de 3 a 5 dígitos, podemos poner los límites en llaves: `pattern:\d{3,5}`
2828

2929
```js run
30-
alert( "I'm not 12, but 1234 years old".match(/\d{3,5}/) ); // "1234"
30+
alert( "No tengo 12, sino 1234 años de edad".match(/\d{3,5}/) ); // "1234"
3131
```
3232

33-
We can omit the upper limit.
33+
Podemos omitir el límite superior
3434

35-
Then a regexp `pattern:\d{3,}` looks for sequences of digits of length `3` or more:
35+
Luego, una regexp `pattern:\d{3,}` busca secuencias de dígitos de longitud `3` o más:
3636

3737
```js run
38-
alert( "I'm not 12, but 345678 years old".match(/\d{3,}/) ); // "345678"
38+
alert( "No tengo 12, sino, 345678 años de edad".match(/\d{3,}/) ); // "345678"
3939
```
4040

41-
Let's return to the string `+7(903)-123-45-67`.
41+
Volvamos a la cadena `+7(903)-123-45-67`.
4242

43-
A number is a sequence of one or more digits in a row. So the regexp is `pattern:\d{1,}`:
43+
Un número es una secuencia de uno o más dígitos continuos. Entonces la expresión regular es `pattern:\d{1,}`:
4444

4545
```js run
4646
let str = "+7(903)-123-45-67";
@@ -50,14 +50,14 @@ let numbers = str.match(/\d{1,}/g);
5050
alert(numbers); // 7,903,123,45,67
5151
```
5252

53-
## Shorthands
53+
## Abreviaciones
5454

55-
There are shorthands for most used quantifiers:
55+
Hay abreviaciones para los cuantificadores más usados:
5656

5757
`pattern:+`
58-
: Means "one or more", the same as `pattern:{1,}`.
58+
: Significa "uno o más", igual que `pattern:{1,}`.
5959

60-
For instance, `pattern:\d+` looks for numbers:
60+
Por ejemplo, `pattern:\d+` busca números:
6161

6262
```js run
6363
let str = "+7(903)-123-45-67";
@@ -66,77 +66,77 @@ There are shorthands for most used quantifiers:
6666
```
6767

6868
`pattern:?`
69-
: Means "zero or one", the same as `pattern:{0,1}`. In other words, it makes the symbol optional.
69+
: Significa "cero o uno", igual que `pattern:{0,1}`. En otras palabras, hace que el símbolo sea opcional.
7070

71-
For instance, the pattern `pattern:ou?r` looks for `match:o` followed by zero or one `match:u`, and then `match:r`.
71+
Por ejemplo, el patrón `pattern:ou?r` busca `match:o` seguido de cero o uno `match:u`, y luego `match:r`.
7272

73-
So, `pattern:colou?r` finds both `match:color` and `match:colour`:
73+
Entonces, `pattern:colou?r` encuentra ambos `match:color` y `match:colour`:
7474

7575
```js run
76-
let str = "Should I write color or colour?";
76+
let str = "¿Debo escribir color o colour?";
7777

7878
alert( str.match(/colou?r/g) ); // color, colour
7979
```
8080

8181
`pattern:*`
82-
: Means "zero or more", the same as `pattern:{0,}`. That is, the character may repeat any times or be absent.
82+
: Significa "cero o más", igual que `pattern:{0,}`. Es decir, el carácter puede repetirse muchas veces o estar ausente.
8383

84-
For example, `pattern:\d0*` looks for a digit followed by any number of zeroes (may be many or none):
84+
Por ejemplo, `pattern:\d0*` busca un dígito seguido de cualquier número de ceros (puede ser muchos o ninguno):
8585

8686
```js run
8787
alert( "100 10 1".match(/\d0*/g) ); // 100, 10, 1
8888
```
8989

90-
Compare it with `pattern:+` (one or more):
90+
Compáralo con `pattern:+` (uno o más):
9191

9292
```js run
9393
alert( "100 10 1".match(/\d0+/g) ); // 100, 10
94-
// 1 not matched, as 0+ requires at least one zero
94+
// 1 no coincide, ya que 0+ requiere al menos un cero
9595
```
9696

97-
## More examples
97+
## Más ejemplos
9898

99-
Quantifiers are used very often. They serve as the main "building block" of complex regular expressions, so let's see more examples.
99+
Los cuantificadores se usan con mucha frecuencia. Sirven como el "bloque de construcción" principal de expresiones regulares complejas, así que veamos más ejemplos.
100100

101-
**Regexp for decimal fractions (a number with a floating point): `pattern:\d+\.\d+`**
101+
**Regexp para fracciones decimales (un número con coma flotante): `pattern:\d+\.\d+`**
102102

103-
In action:
103+
En acción:
104104
```js run
105105
alert( "0 1 12.345 7890".match(/\d+\.\d+/g) ); // 12.345
106106
```
107107

108-
**Regexp for an "opening HTML-tag without attributes", such as `<span>` or `<p>`.**
108+
**Regexp para una "etiqueta HTML de apertura sin atributos", tales como `<span>` o `<p>`.**
109109

110-
1. The simplest one: `pattern:/<[a-z]+>/i`
110+
1. La más simple: `pattern:/<[a-z]+>/i`
111111

112112
```js run
113113
alert( "<body> ... </body>".match(/<[a-z]+>/gi) ); // <body>
114114
```
115115

116-
The regexp looks for character `pattern:'<'` followed by one or more Latin letters, and then `pattern:'>'`.
116+
La regexp busca el carácter `pattern:'<'` seguido de una o más letras latinas, y el carácter `pattern:'>'`.
117117

118-
2. Improved: `pattern:/<[a-z][a-z0-9]*>/i`
118+
2. Mejorada: `pattern:/<[a-z][a-z0-9]*>/i`
119119

120-
According to the standard, HTML tag name may have a digit at any position except the first one, like `<h1>`.
120+
De acuerdo al estándar, el nombre de una etiqueta HTML puede tener un dígito en cualquier posición excepto al inicio, tal como `<h1>`.
121121

122122
```js run
123-
alert( "<h1>Hi!</h1>".match(/<[a-z][a-z0-9]*>/gi) ); // <h1>
123+
alert( "<h1>Hola!</h1>".match(/<[a-z][a-z0-9]*>/gi) ); // <h1>
124124
```
125125

126-
**Regexp "opening or closing HTML-tag without attributes": `pattern:/<\/?[a-z][a-z0-9]*>/i`**
126+
**Regexp para "etiquetas HTML de apertura o cierre sin atributos": `pattern:/<\/?[a-z][a-z0-9]*>/i`**
127127

128-
We added an optional slash `pattern:/?` near the beginning of the pattern. Had to escape it with a backslash, otherwise JavaScript would think it is the pattern end.
128+
Agregamos una barra opcional `pattern:/?` cerca del comienzo del patrón. Se tiene que escapar con una barra diagonal inversa, de lo contrario, JavaScript pensaría que es el final del patrón.
129129

130130
```js run
131-
alert( "<h1>Hi!</h1>".match(/<\/?[a-z][a-z0-9]*>/gi) ); // <h1>, </h1>
131+
alert( "<h1>Hola!</h1>".match(/<\/?[a-z][a-z0-9]*>/gi) ); // <h1>, </h1>
132132
```
133133

134-
```smart header="To make a regexp more precise, we often need make it more complex"
135-
We can see one common rule in these examples: the more precise is the regular expression -- the longer and more complex it is.
134+
```smart header="Para hacer más precisa una regexp, a menudo necesitamos hacerla más compleja"
135+
Podemos ver una regla común en estos ejemplos: cuanto más precisa es la expresión regular, es más larga y compleja.
136136
137-
For instance, for HTML tags we could use a simpler regexp: `pattern:<\w+>`. But as HTML has stricter restrictions for a tag name, `pattern:<[a-z][a-z0-9]*>` is more reliable.
137+
Por ejemplo, para las etiquetas HTML debemos usar una regexp más simple: `pattern:<\w+>`. Pero como HTML tiene normas estrictas para los nombres de etiqueta, `pattern:<[a-z][a-z0-9]*>` es más confiable.
138138
139-
Can we use `pattern:<\w+>` or we need `pattern:<[a-z][a-z0-9]*>`?
139+
¿Podemos usar `pattern:<\w+>` o necesitamos `pattern:<[a-z][a-z0-9]*>`?
140140
141-
In real life both variants are acceptable. Depends on how tolerant we can be to "extra" matches and whether it's difficult or not to remove them from the result by other means.
141+
En la vida real, ambas variantes son aceptables. Depende de cuán tolerantes podamos ser a las coincidencias "adicionales" y si es difícil o no eliminarlas del resultado por otros medios.
142142
```

0 commit comments

Comments
 (0)