Skip to content

Commit 4b9ccb5

Browse files
authored
Merge pull request #237 from cortizg/es.javascript.info.9-01-ri
Patterns and flags
2 parents 9891b7c + 63d4eb5 commit 4b9ccb5

File tree

2 files changed

+82
-79
lines changed

2 files changed

+82
-79
lines changed
Lines changed: 80 additions & 77 deletions
Original file line numberDiff line numberDiff line change
@@ -1,177 +1,180 @@
1-
# Patterns and flags
1+
# Patrones y banderas (flags)
22

3-
Regular expressions are patterns that provide a powerful way to search and replace in text.
3+
Las expresiones regulares son patrones que proporcionan una forma poderosa de buscar y reemplazar texto.
44

5-
In JavaScript, they are available via the [RegExp](mdn:js/RegExp) object, as well as being integrated in methods of strings.
5+
En JavaScript, están disponibles a través del objeto [RegExp](mdn:js/RegExp), además de integrarse en métodos de cadenas.
66

7-
## Regular Expressions
7+
## Expresiones Regulares
88

9-
A regular expression (also "regexp", or just "reg") consists of a *pattern* and optional *flags*.
9+
Una expresión regular (también "regexp", o simplemente "reg") consiste en un *patrón* y *banderas* opcionales.
1010

11-
There are two syntaxes that can be used to create a regular expression object.
1211

13-
The "long" syntax:
12+
Hay dos sintaxis que se pueden usar para crear un objeto de expresión regular.
13+
14+
La sintaxis "larga":
1415

1516
```js
16-
regexp = new RegExp("pattern", "flags");
17+
regexp = new RegExp("patrón", "banderas");
1718
```
1819

19-
And the "short" one, using slashes `"/"`:
20+
Y el "corto", usando barras `"/"`:
2021

2122
```js
22-
regexp = /pattern/; // no flags
23-
regexp = /pattern/gmi; // with flags g,m and i (to be covered soon)
23+
regexp = /pattern/; // sin banderas
24+
regexp = /pattern/gmi; // con banderas g,m e i (para ser cubierto pronto)
2425
```
2526

26-
Slashes `pattern:/.../` tell JavaScript that we are creating a regular expression. They play the same role as quotes for strings.
27+
Las barras `pattern:/.../` le dicen a JavaScript que estamos creando una expresión regular. Juegan el mismo papel que las comillas para las cadenas.
2728

28-
In both cases `regexp` becomes an instance of the built-in `RegExp` class.
29+
En ambos casos, `regexp` se convierte en una instancia de la clase incorporada `RegExp`.
2930

30-
The main difference between these two syntaxes is that pattern using slashes `/.../` does not allow for expressions to be inserted (like string template literals with `${...}`). They are fully static.
31+
La principal diferencia entre estas dos sintaxis es que el patrón que utiliza barras `/.../` no permite que se inserten expresiones (como los literales de plantilla de cadena con `${...}`). Son completamente estáticos.
3132

32-
Slashes are used when we know the regular expression at the code writing time -- and that's the most common situation. While `new RegExp`, is more often used when we need to create a regexp "on the fly" from a dynamically generated string. For instance:
33+
Las barras se utilizan cuando conocemos la expresión regular en el momento de escribir el código, y esa es la situación más común. Mientras que `new RegExp`, se usa con mayor frecuencia cuando necesitamos crear una expresión regular "sobre la marcha" a partir de una cadena generada dinámicamente. Por ejemplo:
3334

3435
```js
35-
let tag = prompt("What tag do you want to find?", "h2");
36+
let tag = prompt("¿Qué etiqueta quieres encontrar?", "h2");
3637

37-
let regexp = new RegExp(`<${tag}>`); // same as /<h2>/ if answered "h2" in the prompt above
38+
igual que /<h2>/ si respondió "h2" en el mensaje anterior
3839
```
3940

40-
## Flags
41+
## Banderas
4142

42-
Regular expressions may have flags that affect the search.
43+
Las expresiones regulares pueden usar banderas que afectan la búsqueda.
4344

44-
There are only 6 of them in JavaScript:
45+
Solo hay 6 de ellas en JavaScript:
4546

4647
`pattern:i`
47-
: With this flag the search is case-insensitive: no difference between `A` and `a` (see the example below).
48+
: Con esta bandera, la búsqueda no distingue entre mayúsculas y minúsculas: no hay diferencia entre `A` y `a` (consulte el ejemplo a continuación).
4849

4950
`pattern:g`
50-
: With this flag the search looks for all matches, without it -- only the first match is returned.
51+
: Con esta bandera, la búsqueda encuentra todas las coincidencias, sin ella, solo se devuelve la primera coincidencia.
5152

5253
`pattern:m`
53-
: Multiline mode (covered in the chapter <info:regexp-multiline-mode>).
54+
: Modo multilínea (cubierto en el capítulo <info:regexp-multiline-mode>).
5455

5556
`pattern:s`
56-
: Enables "dotall" mode, that allows a dot `pattern:.` to match newline character `\n` (covered in the chapter <info:regexp-character-classes>).
57+
: Habilita el modo "dotall", que permite que un punto `pattern:.` coincida con el carácter de línea nueva `\n` (cubierto en el capítulo <info:regexp-character-classes>).
58+
5759

5860
`pattern:u`
59-
: Enables full unicode support. The flag enables correct processing of surrogate pairs. More about that in the chapter <info:regexp-unicode>.
61+
: Permite el soporte completo de Unicode. La bandera permite el procesamiento correcto de pares sustitutos. Más del tema en el capítulo <info:regexp-unicode>.
6062

6163
`pattern:y`
62-
: "Sticky" mode: searching at the exact position in the text (covered in the chapter <info:regexp-sticky>)
64+
: Modo "adhesivo": búsqueda en la posición exacta del texto (cubierto en el capítulo <info:regexp-sticky>)
6365

64-
```smart header="Colors"
65-
From here on the color scheme is:
66+
```smart header="Colores"
67+
A partir de aquí, el esquema de color es:
6668
6769
- regexp -- `pattern:red`
68-
- string (where we search) -- `subject:blue`
69-
- result -- `match:green`
70+
- cadena (donde buscamos) -- `subject:blue`
71+
- resulta -- `match:green`
7072
```
7173

72-
## Searching: str.match
74+
## Buscando: str.match
7375

74-
As mentioned previously, regular expressions are integrated with string methods.
76+
Como se mencionó anteriormente, las expresiones regulares se integran con los métodos de cadena.
7577

76-
The method `str.match(regexp)` finds all matches of `regexp` in the string `str`.
78+
El método `str.match(regex)` busca todas las coincidencias de `regex` en la cadena `str`.
7779

78-
It has 3 working modes:
80+
Tiene 3 modos de trabajo:
7981

80-
1. If the regular expression has flag `pattern:g`, it returns an array of all matches:
82+
1. Si la expresión regular tiene la bandera `pattern:g`, devuelve un arreglo de todas las coincidencias:
8183
```js run
8284
let str = "We will, we will rock you";
8385

84-
alert( str.match(/we/gi) ); // We,we (an array of 2 substrings that match)
86+
alert( str.match(/we/gi) ); // We,we (un arreglo de 2 subcadenas que coinciden)
8587
```
86-
Please note that both `match:We` and `match:we` are found, because flag `pattern:i` makes the regular expression case-insensitive.
88+
Tenga en cuenta que tanto `match:We` como `match: we` se encuentran, porque la bandera `pattern:i` hace que la expresión regular no distinga entre mayúsculas y minúsculas.
8789

88-
2. If there's no such flag it returns only the first match in the form of an array, with the full match at index `0` and some additional details in properties:
90+
2. Si no existe dicha bandera, solo devuelve la primera coincidencia en forma de arreglo, con la coincidencia completa en el índice `0` y algunos detalles adicionales en las propiedades:
8991
```js run
9092
let str = "We will, we will rock you";
9193
92-
let result = str.match(/we/i); // without flag g
94+
let result = str.match(/we/i); // sin la bandera g
9395
94-
alert( result[0] ); // We (1st match)
96+
alert( result[0] ); // We (1ra coincidencia)
9597
alert( result.length ); // 1
9698
97-
// Details:
98-
alert( result.index ); // 0 (position of the match)
99-
alert( result.input ); // We will, we will rock you (source string)
99+
// Detalles:
100+
alert( result.index ); // 0 (posición de la coincidencia)
101+
alert( result.input ); // We will, we will rock you (cadena fuente)
100102
```
101-
The array may have other indexes, besides `0` if a part of the regular expression is enclosed in parentheses. We'll cover that in the chapter <info:regexp-groups>.
103+
El arreglo puede tener otros índices, además de `0` si una parte de la expresión regular está encerrada entre paréntesis. Cubriremos eso en el capítulo <info:regexp-groups>.
102104

103-
3. And, finally, if there are no matches, `null` is returned (doesn't matter if there's flag `pattern:g` or not).
105+
3. Y, finalmente, si no hay coincidencias, se devuelve `null` (no importa si hay una bandera `pattern:g` o no).
104106

105-
This a very important nuance. If there are no matches, we don't receive an empty array, but instead receive `null`. Forgetting about that may lead to errors, e.g.:
107+
Este es un matiz muy importante. Si no hay coincidencias, no recibimos un arreglo vacío, sino que recibimos `null`. Olvidar eso puede conducir a errores, por ejemplo:
106108

107109
```js run
108110
let matches = "JavaScript".match(/HTML/); // = null
109111
110-
if (!matches.length) { // Error: Cannot read property 'length' of null
111-
alert("Error in the line above");
112+
if (!matches.length) { // Error: No se puede leer la propiedad 'length' de null
113+
alert("Error en la línea anterior");
112114
}
113115
```
114116

115-
If we'd like the result to always be an array, we can write it this way:
117+
Si queremos que el resultado sea siempre un arreglo, podemos escribirlo de esta manera:
116118

117119
```js run
118120
let matches = "JavaScript".match(/HTML/)*!* || []*/!*;
119121
120122
if (!matches.length) {
121-
alert("No matches"); // now it works
123+
alert("Sin coincidencias"); // ahora si trabaja
122124
}
123125
```
124126

125-
## Replacing: str.replace
127+
## Reemplazando: str.replace
126128

127-
The method `str.replace(regexp, replacement)` replaces matches found using `regexp` in string `str` with `replacement` (all matches if there's flag `pattern:g`, otherwise, only the first one).
129+
El método `str.replace(regexp, replacement)` reemplaza las coincidencias encontradas usando `regexp` en la cadena `str` con `replacement` (todas las coincidencias si está la bandera `pattern:g`, de lo contrario, solo la primera).
128130

129-
For instance:
131+
Por ejemplo:
130132

131133
```js run
132-
// no flag g
134+
// sin la bandera g
133135
alert( "We will, we will".replace(/we/i, "I") ); // I will, we will
134136
135-
// with flag g
137+
// con la bandera g
136138
alert( "We will, we will".replace(/we/ig, "I") ); // I will, I will
137139
```
138140

139-
The second argument is the `replacement` string. We can use special character combinations in it to insert fragments of the match:
141+
El segundo argumento es la cadena de `replacement`. Podemos usar combinaciones de caracteres especiales para insertar fragmentos de la coincidencia:
140142

141-
| Symbols | Action in the replacement string |
143+
| Símbolos | Acción en la cadena de reemplazo |
142144
|--------|--------|
143-
|`$&`|inserts the whole match|
144-
|<code>$&#096;</code>|inserts a part of the string before the match|
145-
|`$'`|inserts a part of the string after the match|
146-
|`$n`|if `n` is a 1-2 digit number, then it inserts the contents of n-th parentheses, more about it in the chapter <info:regexp-groups>|
147-
|`$<name>`|inserts the contents of the parentheses with the given `name`, more about it in the chapter <info:regexp-groups>|
148-
|`$$`|inserts character `$` |
145+
|`$&`|inserta toda la coincidencia|
146+
|<code>$&#096;</code>|inserta una parte de la cadena antes de la coincidencia|
147+
|`$'`|inserta una parte de la cadena después de la coincidencia|
148+
|`$n`|si `n` es un número de 1-2 dígitos, entonces inserta el contenido de los paréntesis n-ésimo, más del tema en el capítulo <info:regexp-groups>|
149+
|`$<name>`|inserta el contenido de los paréntesis con el `nombre` dado, más del tema en el capítulo <info:regexp-groups>|
150+
|`$$`|inserta el carácter `$` |
149151

150-
An example with `pattern:$&`:
152+
Un ejemplo con `pattern:$&`:
151153

152154
```js run
153-
alert( "I love HTML".replace(/HTML/, "$& and JavaScript") ); // I love HTML and JavaScript
155+
alert( "Me gusta HTML".replace(/HTML/, "$& y JavaScript") ); // Me gusta HTML y JavaScript
154156
```
155157

156-
## Testing: regexp.test
158+
## Pruebas: regexp.test
157159

158-
The method `regexp.test(str)` looks for at least one match, if found, returns `true`, otherwise `false`.
160+
El método `regexp.test(str)` busca al menos una coincidencia, si se encuentra, devuelve `true`, de lo contrario `false`.
159161

160162
```js run
161-
let str = "I love JavaScript";
162-
let regexp = /LOVE/i;
163+
let str = "Me gusta JavaScript";
164+
let regexp = /GUSTA/i;
165+
163166
164167
alert( regexp.test(str) ); // true
165168
```
166169

167-
Later in this chapter we'll study more regular expressions, walk through more examples, and also meet other methods.
170+
Más adelante en este capítulo estudiaremos más expresiones regulares, exploraremos más ejemplos y también conoceremos otros métodos.
168171

169-
Full information about the methods is given in the article <info:regexp-methods>.
172+
La información completa sobre métodos se proporciona en el artículo <info:regexp-method>.
170173

171-
## Summary
174+
## Resumen
172175

173-
- A regular expression consists of a pattern and optional flags: `pattern:g`, `pattern:i`, `pattern:m`, `pattern:u`, `pattern:s`, `pattern:y`.
174-
- Without flags and special symbols (that we'll study later), the search by a regexp is the same as a substring search.
175-
- The method `str.match(regexp)` looks for matches: all of them if there's `pattern:g` flag, otherwise, only the first one.
176-
- The method `str.replace(regexp, replacement)` replaces matches found using `regexp` with `replacement`: all of them if there's `pattern:g` flag, otherwise only the first one.
177-
- The method `regexp.test(str)` returns `true` if there's at least one match, otherwise, it returns `false`.
176+
- Una expresión regular consiste en un patrón y banderas opcionales: `pattern:g`, `pattern:i`, `pattern:m`, `pattern:u`, `pattern:s`, `pattern:y`.
177+
- Sin banderas y símbolos especiales (que estudiaremos más adelante), la búsqueda por expresión regular es lo mismo que una búsqueda de subcadena.
178+
- El método `str.match(regexp)` busca coincidencias: devuelve todas si hay una bandera `pattern:g`, de lo contrario, solo la primera.
179+
- El método `str.replace(regexp, replacement)` reemplaza las coincidencias encontradas usando `regexp` con `replacement`: devuelve todas si hay una bandera `pattern:g`, de lo contrario solo la primera.
180+
- El método `regexp.test(str)` devuelve `true` si hay al menos una coincidencia, de lo contrario, devuelve `false`.

9-regular-expressions/index.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
1-
# Regular expressions
1+
# Expresiones Regulares
22

3-
Regular expressions is a powerful way of doing search and replace in strings.
3+
Las expresiones regulares son una forma poderosa de hacer búsqueda y reemplazo de cadenas.

0 commit comments

Comments
 (0)