You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: 9-regular-expressions/12-regexp-backreferences/article.md
+22-22Lines changed: 22 additions & 22 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,33 +1,33 @@
1
-
# Backreferences in pattern: \N and \k<name>
1
+
# Referencias inversas en patrones: \N y \k<nombre>
2
2
3
-
We can use the contents of capturing groups `pattern:(...)`not only in the result or in the replacement string, but also in the pattern itself.
3
+
Podemos utilizar el contenido de los grupos de captura `pattern:(...)`no solo en el resultado o en la cadena de reemplazo, sino también en el patrón en sí.
4
4
5
-
## Backreference by number: \N
5
+
## Referencia inversa por número: \N
6
6
7
-
A group can be referenced in the pattern using `pattern:\N`, where`N`is the group number.
7
+
Se puede hacer referencia a un grupo en el patrón usando `pattern:\N`, donde`N`es el número de grupo.
8
8
9
-
To make clear why that's helpful, let's consider a task.
9
+
Para aclarar por qué es útil, consideremos una tarea.
10
10
11
-
We need to find quoted strings: either single-quoted `subject:'...'`or a double-quoted`subject:"..."` -- both variants should match.
11
+
Necesitamos encontrar una cadena entre comillas: con cualquiera de los dos tipos, comillas simples `subject:'...'`o comillas dobles`subject:"..."` -- ambas variantes deben coincidir.
12
12
13
-
How to find them?
13
+
¿Cómo encontrarlas?
14
14
15
-
We can put both kinds of quotes in the square brackets: `pattern:['"](.*?)['"]`, but it would find strings with mixed quotes, like`match:"...'`and`match:'..."`. That would lead to incorrect matches when one quote appears inside other ones, like in the string`subject:"She's the one!"`:
15
+
Ambos tipos de comillas se pueden poner entre corchetes: `pattern:['"](.*?)['"]`, pero encontrará cadenas con comillas mixtas, como`match:"...'`y`match:'..."`. Eso conduciría a coincidencias incorrectas cuando una cita aparece dentro de otra., como en la cadena`subject:"She's the one!"` (en este ejemplo los strings no se traducen por el uso de la comilla simple):
16
16
17
17
```js run
18
18
let str =`He said: "She's the one!".`;
19
19
20
20
let regexp =/['"](.*?)['"]/g;
21
21
22
-
//The result is not what we'd like to have
22
+
//El resultado no es el que nos gustaría tener
23
23
alert( str.match(regexp) ); // "She'
24
24
```
25
25
26
-
As we can see, the pattern found an opening quote`match:"`, then the text is consumed till the other quote `match:'`, that closes the match.
26
+
Como podemos ver, el patrón encontró una cita abierta`match:"`, luego se consume el texto hasta encontrar la siguiente comilla `match:'`, esta cierra la coincidencia.
27
27
28
-
To make sure that the pattern looks for the closing quote exactly the same as the opening one, we can wrap it into a capturing group and backreference it: `pattern:(['"])(.*?)\1`.
28
+
Para asegurar que el patrón busque la comilla de cierre exactamente igual que la de apertura, se pone dentro de un grupo de captura y se hace referencia inversa al 1ero: `pattern:(['"])(.*?)\1`.
29
29
30
-
Here's the correct code:
30
+
Aquí está el código correcto:
31
31
32
32
```js run
33
33
let str =`He said: "She's the one!".`;
@@ -39,27 +39,27 @@ let regexp = /(['"])(.*?)\1/g;
39
39
alert( str.match(regexp) ); // "She's the one!"
40
40
```
41
41
42
-
Now it works! The regular expression engine finds the first quote `pattern:(['"])`and memorizes its content. That's the first capturing group.
42
+
¡Ahora funciona! El motor de expresiones regulares encuentra la primera comilla `pattern:(['"])`y memoriza su contenido. Este es el primer grupo de captura.
43
43
44
-
Further in the pattern`pattern:\1`means "find the same text as in the first group", exactly the same quote in our case.
44
+
continuando en el patrón,`pattern:\1`significa "encuentra el mismo texto que en el primer grupo", en nuestro caso exactamente la misma comilla.
45
45
46
-
Similar to that, `pattern:\2`would mean the contents of the second group, `pattern:\3` - the 3rd group, and so on.
46
+
Similar a esto, `pattern:\2`debería significar: el contenido del segundo grupo, `pattern:\3` - del tercer grupo, y así sucesivamente.
47
47
48
48
```smart
49
-
If we use `?:` in the group, then we can't reference it. Groups that are excluded from capturing `(?:...)` are not memorized by the engine.
49
+
Si usamos `?:` en el grupo, entonces no lo podremos referenciar. Los grupos que se excluyen de las capturas `(?:...)` no son memorizados por el motor.
50
50
```
51
51
52
-
```warn header="Don't mess up: in the pattern `pattern:\1`, in the replacement: `pattern:$1`"
53
-
In the replacement string we use a dollar sign: `pattern:$1`, while in the pattern - a backslash`pattern:\1`.
52
+
```warn header="No confundas: el patrón `pattern:\1`, con el reemplazo: `pattern:$1`"
53
+
En el reemplazo de cadenas usamos el signo dólar: `pattern:$1`, mientras que en el patrón - una barra invertida`pattern:\1`.
54
54
```
55
55
56
-
## Backreference by name: `\k<name>`
56
+
## Referencia inversa por nombre: `\k<nombre>`
57
57
58
-
If a regexp has many parentheses, it's convenient to give them names.
58
+
Si una regexp tiene muchos paréntesis, es conveniente asignarle nombres.
59
59
60
-
To reference a named group we can use `pattern:\k<name>`.
60
+
Para referenciar un grupo con nombre usamos `pattern:\k<nombre>`.
61
61
62
-
In the example below the group with quotes is named `pattern:?<quote>`, so the backreference is `pattern:\k<quote>`:
62
+
En el siguiente ejemplo, el grupo con comillas se llama `pattern:?<quote>`, entonces la referencia inversa es `pattern:\k<quote>`:
0 commit comments