Skip to content

Commit 7ea15bd

Browse files
authored
Merge pull request #473 from vplentinax/or
Alternation (OR) |
2 parents 9d9884b + eeb7ba4 commit 7ea15bd

File tree

9 files changed

+83
-83
lines changed

9 files changed

+83
-83
lines changed

9-regular-expressions/13-regexp-alternation/01-find-programming-language/solution.md

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

2-
The first idea can be to list the languages with `|` in-between.
2+
La primera idea puede ser listar los idiomas con `|` en el medio.
33

4-
But that doesn't work right:
4+
Pero eso no funciona bien:
55

66
```js run
77
let regexp = /Java|JavaScript|PHP|C|C\+\+/g;
@@ -11,18 +11,18 @@ let str = "Java, JavaScript, PHP, C, C++";
1111
alert( str.match(regexp) ); // Java,Java,PHP,C,C
1212
```
1313

14-
The regular expression engine looks for alternations one-by-one. That is: first it checks if we have `match:Java`, otherwise -- looks for `match:JavaScript` and so on.
14+
El motor de expresiones regulares busca las alternancias una por una. Es decir: primero verifica si tenemos `match: Java`, de lo contrario - busca `match: JavaScript` y así sucesivamente.
1515

16-
As a result, `match:JavaScript` can never be found, just because `match:Java` is checked first.
16+
Como resultado, nunca se puede encontrar `match: JavaScript`, simplemente porque encuentra primero `match: Java`.
1717

18-
The same with `match:C` and `match:C++`.
18+
Lo mismo con `match: C` y `match: C++ `.
1919

20-
There are two solutions for that problem:
20+
Hay dos soluciones para ese problema:
2121

22-
1. Change the order to check the longer match first: `pattern:JavaScript|Java|C\+\+|C|PHP`.
23-
2. Merge variants with the same start: `pattern:Java(Script)?|C(\+\+)?|PHP`.
22+
1. Cambiar el orden para comprobar primero la coincidencia más larga: `pattern:JavaScript|Java|C\+\+|C|PHP`.
23+
2. Fusionar variantes con el mismo inicio: `pattern:Java(Script)?|C(\+\+)?|PHP`.
2424

25-
In action:
25+
En acción:
2626

2727
```js run
2828
let regexp = /Java(Script)?|C(\+\+)?|PHP/g;

9-regular-expressions/13-regexp-alternation/01-find-programming-language/task.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
1-
# Find programming languages
1+
# Encuentra lenguajes de programación
22

3-
There are many programming languages, for instance Java, JavaScript, PHP, C, C++.
3+
Hay muchos lenguajes de programación, por ejemplo, Java, JavaScript, PHP, C, C ++.
44

5-
Create a regexp that finds them in the string `subject:Java JavaScript PHP C++ C`:
5+
Crea una expresión regular que los encuentre en la cadena `subject:Java JavaScript PHP C++ C`:
66

77
```js
88
let regexp = /your regexp/g;

9-regular-expressions/13-regexp-alternation/02-find-matching-bbtags/solution.md

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11

2-
Opening tag is `pattern:\[(b|url|quote)\]`.
2+
La etiqueta de apertura es `pattern:\[(b|url|quote)\]`.
33

4-
Then to find everything till the closing tag -- let's use the pattern `pattern:.*?` with flag `pattern:s` to match any character including the newline and then add a backreference to the closing tag.
4+
Luego, para encontrar todo hasta la etiqueta de cierre, usemos el patrón`pattern:.*?` con la bandera `pattern:s` para que coincida con cualquier carácter, incluida la nueva línea, y luego agreguemos una referencia inversa a la etiqueta de cierre.
55

6-
The full pattern: `pattern:\[(b|url|quote)\].*?\[/\1\]`.
6+
El patrón completo: `pattern:\[(b|url|quote)\].*?\[/\1\]`.
77

8-
In action:
8+
En acción:
99

1010
```js run
1111
let regexp = /\[(b|url|quote)\].*?\[\/\1\]/gs;
@@ -20,4 +20,4 @@ let str = `
2020
alert( str.match(regexp) ); // [b]hello![/b],[quote][url]http://google.com[/url][/quote]
2121
```
2222

23-
Please note that besides escaping `pattern:[` and `pattern:]`, we had to escape a slash for the closing tag `pattern:[\/\1]`, because normally the slash closes the pattern.
23+
Tenga en cuenta que además de escapar `pattern:[` y `pattern:]`, tuvimos que escapar de una barra para la etiqueta de cierre `pattern:[\/\1]`, porque normalmente la barra cierra el patrón.

9-regular-expressions/13-regexp-alternation/02-find-matching-bbtags/task.md

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,35 +1,35 @@
1-
# Find bbtag pairs
1+
# Encuentra la pareja bbtag
22

3-
A "bb-tag" looks like `[tag]...[/tag]`, where `tag` is one of: `b`, `url` or `quote`.
3+
Un "bb-tag" se ve como `[tag]...[/tag]`, donde `tag` es uno de: `b`, `url` o `quote`.
44

5-
For instance:
5+
Por ejemplo:
66
```
77
[b]text[/b]
88
[url]http://google.com[/url]
99
```
1010

11-
BB-tags can be nested. But a tag can't be nested into itself, for instance:
11+
BB-tags se puede anidar. Pero una etiqueta no se puede anidar en sí misma, por ejemplo:
1212

1313
```
1414
Normal:
1515
[url] [b]http://google.com[/b] [/url]
1616
[quote] [b]text[/b] [/quote]
1717
18-
Can't happen:
18+
No puede suceder:
1919
[b][b]text[/b][/b]
2020
```
2121

22-
Tags can contain line breaks, that's normal:
22+
Las etiquetas pueden contener saltos de línea, eso es normal:
2323

2424
```
2525
[quote]
2626
[b]text[/b]
2727
[/quote]
2828
```
2929

30-
Create a regexp to find all BB-tags with their contents.
30+
Cree una expresión regular para encontrar todas las BB-tags con su contenido.
3131

32-
For instance:
32+
Por ejemplo:
3333

3434
```js
3535
let regexp = /your regexp/flags;
@@ -38,7 +38,7 @@ let str = "..[url]http://google.com[/url]..";
3838
alert( str.match(regexp) ); // [url]http://google.com[/url]
3939
```
4040

41-
If tags are nested, then we need the outer tag (if we want we can continue the search in its content):
41+
Si las etiquetas están anidadas, entonces necesitamos la etiqueta externa (si queremos podemos continuar la búsqueda en su contenido):
4242

4343
```js
4444
let regexp = /your regexp/flags;

9-regular-expressions/13-regexp-alternation/03-match-quoted-string/solution.md

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
1-
The solution: `pattern:/"(\\.|[^"\\])*"/g`.
1+
La solución: `pattern:/"(\\.|[^"\\])*"/g`.
22

3-
Step by step:
3+
El paso a paso:
44

5-
- First we look for an opening quote `pattern:"`
6-
- Then if we have a backslash `pattern:\\` (we technically have to double it in the pattern, because it is a special character, so that's a single backslash in fact), then any character is fine after it (a dot).
7-
- Otherwise we take any character except a quote (that would mean the end of the string) and a backslash (to prevent lonely backslashes, the backslash is only used with some other symbol after it): `pattern:[^"\\]`
8-
- ...And so on till the closing quote.
5+
- Primero buscamos una comilla de apertura `pattern:"`
6+
- Entonces, si tenemos una barra invertida `pattern:\\` (tenemos que duplicarla en el patrón porque es un carácter especial), y luego cualquier carácter está bien después de él (un punto).
7+
- De lo contrario, tomamos cualquier carácter excepto una comilla (que significaría el final de la cadena) y una barra invertida (para evitar barras invertidas solitarias, la barra invertida solo se usa con algún otro símbolo después): `pattern:[^"\\]`
8+
- ...Y así sucesivamente hasta la comilla de cierre.
99

10-
In action:
10+
En acción:
1111

1212
```js run
1313
let regexp = /"(\\.|[^"\\])*"/g;

9-regular-expressions/13-regexp-alternation/03-match-quoted-string/task.md

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,28 @@
1-
# Find quoted strings
1+
# Encuentra cadenas entre comillas
22

3-
Create a regexp to find strings in double quotes `subject:"..."`.
3+
Crea una expresión regular para encontrar cadenas entre comillas dobles `subject:"..."`.
44

5-
The strings should support escaping, the same way as JavaScript strings do. For instance, quotes can be inserted as `subject:\"` a newline as `subject:\n`, and the slash itself as `subject:\\`.
5+
Las cadenas deben admitir el escape, de la misma manera que lo hacen las cadenas de JavaScript. Por ejemplo, las comillas se pueden insertar como `subject:\"` ,una nueva línea como `subject:\n`, y la doble barra invertida como `subject:\\`.
66

77
```js
88
let str = "Just like \"here\".";
99
```
1010

11-
Please note, in particular, that an escaped quote `subject:\"` does not end a string.
11+
Tenga en cuenta, en particular, que una comilla escapada `subject:\"` no termina una cadena.
1212

13-
So we should search from one quote to the other ignoring escaped quotes on the way.
13+
Por lo tanto, deberíamos buscar de una comilla a otra (la de cierre), ignorando las comillas escapadas en el camino.
1414

15-
That's the essential part of the task, otherwise it would be trivial.
15+
Esa es la parte esencial de la tarea, de lo contrario sería trivial.
1616

17-
Examples of strings to match:
17+
Ejemplos de cadenas para hacer coincidir:
1818
```js
1919
.. *!*"test me"*/!* ..
20-
.. *!*"Say \"Hello\"!"*/!* ... (escaped quotes inside)
21-
.. *!*"\\"*/!* .. (double slash inside)
22-
.. *!*"\\ \""*/!* .. (double slash and an escaped quote inside)
20+
.. *!*"Say \"Hello\"!"*/!* ... (comillas escapadas dentro)
21+
.. *!*"\\"*/!* .. (doble barra invertida dentro)
22+
.. *!*"\\ \""*/!* .. (doble barra y comilla escapada dentro.)
2323
```
2424

25-
In JavaScript we need to double the slashes to pass them right into the string, like this:
25+
En JavaScript, necesitamos duplicar las barras para pasarlas directamente a la cadena, así:
2626

2727
```js run
2828
let str = ' .. "test me" .. "Say \\"Hello\\"!" .. "\\\\ \\"" .. ';

9-regular-expressions/13-regexp-alternation/04-match-exact-tag/solution.md

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
11

2-
The pattern start is obvious: `pattern:<style`.
2+
El inicio del patrón es obvio: `pattern:<style`.
33

4-
...But then we can't simply write `pattern:<style.*?>`, because `match:<styler>` would match it.
4+
...Pero entonces no podemos simplemente escribir `pattern:<style.*?>`, porque `match:<styler>` coincidiría.
55

6-
We need either a space after `match:<style` and then optionally something else or the ending `match:>`.
6+
Necesitamos un espacio después `match:<style` y luego, opcionalmente, algo más o el final `match:>`.
77

8-
In the regexp language: `pattern:<style(>|\s.*?>)`.
8+
En el lenguaje de expresión regular: `pattern:<style(>|\s.*?>)`.
99

10-
In action:
10+
En acción:
1111

1212
```js run
1313
let regexp = /<style(>|\s.*?>)/g;

9-regular-expressions/13-regexp-alternation/04-match-exact-tag/task.md

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
1-
# Find the full tag
1+
# Encuentra la etiqueta completa
22

3-
Write a regexp to find the tag `<style...>`. It should match the full tag: it may have no attributes `<style>` or have several of them `<style type="..." id="...">`.
3+
Escriba una expresión regular para encontrar la etiqueta `<style...>`. Debe coincidir con la etiqueta completa: puede no tener atributos `<style>` o tener varios de ellos `<style type="..." id="...">`.
44

5-
...But the regexp should not match `<styler>`!
5+
...¡Pero la expresión regular no debería coincidir con `<styler>`!
66

7-
For instance:
7+
Por ejemplo:
88

99
```js
1010
let regexp = /your regexp/g;

9-regular-expressions/13-regexp-alternation/article.md

Lines changed: 30 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,67 +1,67 @@
1-
# Alternation (OR) |
1+
# Altarnancia (OR (O)) |
22

3-
Alternation is the term in regular expression that is actually a simple "OR".
3+
Alternancia es un término en expresión regular que simplemente significa "O".
44

5-
In a regular expression it is denoted with a vertical line character `pattern:|`.
5+
En una expresión regular se denota con un carácter de línea vertical `pattern:|`.
66

7-
For instance, we need to find programming languages: HTML, PHP, Java or JavaScript.
7+
Por ejemplo, necesitamos encontrar lenguajes de programación: HTML, PHP, Java o JavaScript.
88

9-
The corresponding regexp: `pattern:html|php|java(script)?`.
9+
La expresión regular correspondiente es: `pattern:html|php|java(script)?`.
1010

11-
A usage example:
11+
Un ejemplo de uso:
1212

1313
```js run
1414
let regexp = /html|php|css|java(script)?/gi;
1515

16-
let str = "First HTML appeared, then CSS, then JavaScript";
16+
let str = "Primera aparición de HTML, luego CSS, luego JavaScript";
1717

1818
alert( str.match(regexp) ); // 'HTML', 'CSS', 'JavaScript'
1919
```
2020

21-
We already saw a similar thing -- square brackets. They allow to choose between multiple characters, for instance `pattern:gr[ae]y` matches `match:gray` or `match:grey`.
21+
Ya vimos algo similar: corchetes. Permiten elegir entre varios caracteres, por ejemplo `pattern:gr[ae]y` coincide con `match:gray` o `match:grey`.
2222

23-
Square brackets allow only characters or character classes. Alternation allows any expressions. A regexp `pattern:A|B|C` means one of expressions `A`, `B` or `C`.
23+
Los corchetes solo permiten caracteres o conjuntos de caracteres. La alternancia permite cualquier expresión. Una expresión regular `pattern:A|B|C` significa una de las expresiones `A`, `B` o `C`.
2424

25-
For instance:
25+
Por ejemplo:
2626

27-
- `pattern:gr(a|e)y` means exactly the same as `pattern:gr[ae]y`.
28-
- `pattern:gra|ey` means `match:gra` or `match:ey`.
27+
- `pattern:gr(a|e)y` significa exactamente lo mismo que `pattern:gr[ae]y`.
28+
- `pattern:gra|ey` significa `match:gra` o `match:ey`.
2929

30-
To apply alternation to a chosen part of the pattern, we can enclose it in parentheses:
31-
- `pattern:I love HTML|CSS` matches `match:I love HTML` or `match:CSS`.
32-
- `pattern:I love (HTML|CSS)` matches `match:I love HTML` or `match:I love CSS`.
30+
Para aplicar la alternancia a una parte elegida del patrón, podemos encerrarla entre paréntesis:
31+
- `pattern:I love HTML|CSS` coincide con `match:I love HTML` o `match:CSS`.
32+
- `pattern:I love (HTML|CSS)` coincide con `match:I love HTML` o `match:I love CSS`.
3333

34-
## Example: regexp for time
34+
## Ejemplo: Expresión regular para el tiempo
3535

36-
In previous articles there was a task to build a regexp for searching time in the form `hh:mm`, for instance `12:00`. But a simple `pattern:\d\d:\d\d` is too vague. It accepts `25:99` as the time (as 99 minutes match the pattern, but that time is invalid).
36+
En artículos anteriores había una tarea para construir una expresión regular para buscar un horario en la forma `hh:mm`, por ejemplo `12:00`. Pero esta simple expresión `pattern:\d\d:\d\d` es muy vaga. Acepta `25:99` como tiempo (ya que 99 segundos coinciden con el patrón, pero ese tiempo no es válido).
3737

38-
How can we make a better pattern?
38+
¿Cómo podemos hacer un mejor patrón?
3939

40-
We can use more careful matching. First, the hours:
40+
Podemos utilizar una combinación más cuidadosa. Primero, las horas:
4141

42-
- If the first digit is `0` or `1`, then the next digit can be any: `pattern:[01]\d`.
43-
- Otherwise, if the first digit is `2`, then the next must be `pattern:[0-3]`.
44-
- (no other first digit is allowed)
42+
- Si el primer dígito es `0` o `1`, entonces el siguiente dígito puede ser cualquiera: `pattern:[01]\d`.
43+
- De otra manera, si el primer dígito es `2`, entonces el siguiente debe ser `pattern:[0-3]`.
44+
- (no se permite ningún otro dígito)
4545

46-
We can write both variants in a regexp using alternation: `pattern:[01]\d|2[0-3]`.
46+
Podemos escribir ambas variantes en una expresión regular usando alternancia: `pattern:[01]\d|2[0-3]`.
4747

48-
Next, minutes must be from `00` to `59`. In the regular expression language that can be written as `pattern:[0-5]\d`: the first digit `0-5`, and then any digit.
48+
A continuación, los minutos deben estar comprendidos entre `00` y `59`. En el lenguaje de expresiones regulares que se puede escribir como `pattern:[0-5]\d`: el primer dígito `0-5`, y luego culquier otro.
4949

50-
If we glue hours and minutes together, we get the pattern: `pattern:[01]\d|2[0-3]:[0-5]\d`.
50+
Si pegamos minutos y segundos juntos, obtenemos el patrón: `pattern:[01]\d|2[0-3]:[0-5]\d`.
5151

52-
We're almost done, but there's a problem. The alternation `pattern:|` now happens to be between `pattern:[01]\d` and `pattern:2[0-3]:[0-5]\d`.
52+
Ya casi terminamos, pero hay un problema. La alternancia `pattern:|` ahora pasa a estar entre `pattern:[01]\d` y `pattern:2[0-3]:[0-5]\d`.
5353

54-
That is: minutes are added to the second alternation variant, here's a clear picture:
54+
Es decir: se agregan minutos a la segunda variante de alternancia, aquí hay una imagen clara:
5555

5656
```
5757
[01]\d | 2[0-3]:[0-5]\d
5858
```
5959

60-
That pattern looks for `pattern:[01]\d` or `pattern:2[0-3]:[0-5]\d`.
60+
Este patrón busca `pattern:[01]\d` o `pattern:2[0-3]:[0-5]\d`.
6161

62-
But that's wrong, the alternation should only be used in the "hours" part of the regular expression, to allow `pattern:[01]\d` OR `pattern:2[0-3]`. Let's correct that by enclosing "hours" into parentheses: `pattern:([01]\d|2[0-3]):[0-5]\d`.
62+
Pero eso es incorrecto, la alternancia solo debe usarse en la parte "horas" de la expresión regular, para permitir `pattern:[01]\d` O `pattern:2[0-3]`. Corregiremos eso encerrando las "horas" entre paréntesis: `pattern:([01]\d|2[0-3]):[0-5]\d`.
6363

64-
The final solution:
64+
La solución final sería:
6565

6666
```js run
6767
let regexp = /([01]\d|2[0-3]):[0-5]\d/g;

0 commit comments

Comments
 (0)