-
Notifications
You must be signed in to change notification settings - Fork 228
Patterns and flags #237
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
vplentinax
merged 26 commits into
javascript-tutorial:master
from
cortizg:es.javascript.info.9-01-ri
Jun 11, 2020
Merged
Patterns and flags #237
Changes from 1 commit
Commits
Show all changes
26 commits
Select commit
Hold shift + click to select a range
bf9ca5f
9-01-ri Traducido 18
cortizg cbb314c
Update 9-regular-expressions/01-regexp-introduction/article.md
cortizg f8f5b42
Update 9-regular-expressions/01-regexp-introduction/article.md
cortizg 70ef326
Update 9-regular-expressions/01-regexp-introduction/article.md
cortizg d3bc30b
Update 9-regular-expressions/01-regexp-introduction/article.md
cortizg fd70dcd
Update 9-regular-expressions/01-regexp-introduction/article.md
cortizg 056e544
Update 9-regular-expressions/01-regexp-introduction/article.md
cortizg 5dea5ad
Update 9-regular-expressions/01-regexp-introduction/article.md
cortizg e33ec5b
Update 9-regular-expressions/01-regexp-introduction/article.md
cortizg eba3900
Update 9-regular-expressions/01-regexp-introduction/article.md
cortizg 550039e
Update 9-regular-expressions/01-regexp-introduction/article.md
cortizg 834ac1a
Update 9-regular-expressions/01-regexp-introduction/article.md
cortizg 31afb25
Update 9-regular-expressions/01-regexp-introduction/article.md
cortizg 44e59d9
Update 9-regular-expressions/01-regexp-introduction/article.md
cortizg 9c34e07
Update 9-regular-expressions/01-regexp-introduction/article.md
cortizg 43196a1
Update 9-regular-expressions/01-regexp-introduction/article.md
cortizg b285a9e
Update 9-regular-expressions/01-regexp-introduction/article.md
cortizg d8e9a54
Update 9-regular-expressions/01-regexp-introduction/article.md
cortizg b992920
Update 9-regular-expressions/01-regexp-introduction/article.md
cortizg 98c112e
Update 9-regular-expressions/01-regexp-introduction/article.md
cortizg e33144e
Update 9-regular-expressions/01-regexp-introduction/article.md
cortizg ee79bcd
Update 9-regular-expressions/01-regexp-introduction/article.md
cortizg dfab9af
Update 9-regular-expressions/01-regexp-introduction/article.md
cortizg 90232f0
Update 9-regular-expressions/01-regexp-introduction/article.md
cortizg 769ec75
Merge branch 'master' into es.javascript.info.9-01-ri
cortizg 63d4eb5
Update 9-regular-expressions/01-regexp-introduction/article.md
cortizg File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
190 changes: 120 additions & 70 deletions
190
9-regular-expressions/01-regexp-introduction/article.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,127 +1,177 @@ | ||
# Patterns and flags | ||
# Patrones y flags | ||
|
||
Regular expressions is a powerful way of searching and replacing inside a string. | ||
Las expresiones regulares son patrones que proporcionan una forma poderosa de buscar y reemplazar texto. | ||
|
||
In JavaScript regular expressions are implemented using objects of a built-in `RegExp` class and integrated with strings. | ||
En JavaScript, están disponibles a través del objeto [RegExp](mdn:js/RegExp), además de integrarse en métodos de cadenas. | ||
|
||
Please note that regular expressions vary between programming languages. In this tutorial we concentrate on JavaScript. Of course there's a lot in common, but they are a somewhat different in Perl, Ruby, PHP etc. | ||
## Expresiones Regulares | ||
|
||
## Regular expressions | ||
Una expresión regular (también "regexp", o simplemente "reg") consiste en un *patrón* y *flags* opcionales. | ||
cortizg marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
A regular expression (also "regexp", or just "reg") consists of a *pattern* and optional *flags*. | ||
Hay dos sintaxis que se pueden usar para crear un objeto de expresión regular. | ||
|
||
There are two syntaxes to create a regular expression object. | ||
|
||
The long syntax: | ||
La sintaxis "larga": | ||
|
||
```js | ||
regexp = new RegExp("pattern", "flags"); | ||
regexp = new RegExp("patrón", "flags"); | ||
cortizg marked this conversation as resolved.
Show resolved
Hide resolved
cortizg marked this conversation as resolved.
Show resolved
Hide resolved
|
||
``` | ||
|
||
...And the short one, using slashes `"/"`: | ||
Y el "corto", usando barras `"/"`: | ||
|
||
```js | ||
regexp = /pattern/; // no flags | ||
regexp = /pattern/gmi; // with flags g,m and i (to be covered soon) | ||
regexp = /pattern/; // sin flags | ||
cortizg marked this conversation as resolved.
Show resolved
Hide resolved
cortizg marked this conversation as resolved.
Show resolved
Hide resolved
|
||
regexp = /pattern/gmi; // con flags g,m e i (para ser cubierto pronto) | ||
cortizg marked this conversation as resolved.
Show resolved
Hide resolved
|
||
``` | ||
|
||
Slashes `"/"` tell JavaScript that we are creating a regular expression. They play the same role as quotes for strings. | ||
Las barras `pattern:/.../` le dicen a JavaScript que estamos creando una expresión regular. Juegan el mismo papel que las comillas para las cadenas. | ||
|
||
## Usage | ||
En ambos casos, `regexp` se convierte en una instancia de la clase incorporada `RegExp`. | ||
|
||
To search inside a string, we can use method [search](mdn:js/String/search). | ||
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. | ||
|
||
Here's an example: | ||
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: | ||
|
||
```js run | ||
let str = "I love JavaScript!"; // will search here | ||
```js | ||
let tag = prompt("¿Qué etiqueta quieres encontrar?", "h2"); | ||
|
||
let regexp = /love/; | ||
alert( str.search(regexp) ); // 2 | ||
igual que /<h2>/ si respondió "h2" en el mensaje anterior | ||
``` | ||
|
||
The `str.search` method looks for the pattern `pattern:/love/` and returns the position inside the string. As we might guess, `pattern:/love/` is the simplest possible pattern. What it does is a simple substring search. | ||
## Flags | ||
cortizg marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
The code above is the same as: | ||
Las expresiones regulares pueden usar flags que afectan la búsqueda. | ||
cortizg marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
```js run | ||
let str = "I love JavaScript!"; // will search here | ||
Solo hay 6 de ellas en JavaScript: | ||
|
||
let substr = 'love'; | ||
alert( str.search(substr) ); // 2 | ||
``` | ||
`pattern:i` | ||
: Con esta flag, la búsqueda no distingue entre mayúsculas y minúsculas: no hay diferencia entre `A` y `a` (consulte el ejemplo a continuación). | ||
cortizg marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
`pattern:g` | ||
: Con esta flag, la búsqueda encuentra todas las coincidencias, sin ella, solo se devuelve la primera coincidencia. | ||
cortizg marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
So searching for `pattern:/love/` is the same as searching for `"love"`. | ||
`pattern:m` | ||
: Modo multilínea (cubierto en el capítulo <info:regexp-multiline-mode>). | ||
|
||
But that's only for now. Soon we'll create more complex regular expressions with much more searching power. | ||
`pattern:s` | ||
: 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>). | ||
|
||
```smart header="Colors" | ||
From here on the color scheme is: | ||
`pattern:u` | ||
: Permite el soporte completo de Unicode. La flag permite el procesamiento correcto de pares sustitutos. Más del tema en el capítulo <info:regexp-unicode>. | ||
cortizg marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
`pattern:y` | ||
: Modo "adhesivo": búsqueda en la posición exacta del texto (cubierto en el capítulo <info:regexp-sticky>) | ||
|
||
```smart header="Colores" | ||
A partir de aquí, el esquema de color es: | ||
|
||
- regexp -- `pattern:red` | ||
- string (where we search) -- `subject:blue` | ||
- result -- `match:green` | ||
- cadena (donde buscamos) -- `subject:blue` | ||
- resulta -- `match:green` | ||
``` | ||
|
||
## Buscando: str.match | ||
|
||
````smart header="When to use `new RegExp`?" | ||
Normally we use the short syntax `/.../`. But it does not support variable insertions `${...}`. | ||
Como se mencionó anteriormente, las expresiones regulares se integran con los métodos de cadena. | ||
|
||
On the other hand, `new RegExp` allows to construct a pattern dynamically from a string, so it's more flexible. | ||
El método `str.match(regex)` busca todas las coincidencias de `regex` en la cadena `str`. | ||
|
||
Here's an example of a dynamically generated regexp: | ||
Tiene 3 modos de trabajo: | ||
|
||
```js run | ||
let tag = prompt("Which tag you want to search?", "h2"); | ||
let regexp = new RegExp(`<${tag}>`); | ||
1. Si la expresión regular tiene la flag `pattern:g`, devuelve un arreglo de todas las coincidencias: | ||
cortizg marked this conversation as resolved.
Show resolved
Hide resolved
|
||
```js run | ||
let str = "We will, we will rock you"; | ||
|
||
// finds <h2> by default | ||
alert( "<h1> <h2> <h3>".search(regexp)); | ||
``` | ||
```` | ||
alert( str.match(/we/gi) ); // We,we (un arreglo de 2 subcadenas que coinciden) | ||
``` | ||
Tenga en cuenta que tanto `match:We` como `match: we` se encuentran, porque la flag `pattern:i` hace que la expresión regular no distinga entre mayúsculas y minúsculas. | ||
cortizg marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
2. Si no existe dicha flag, solo devuelve la primera coincidencia en forma de arreglo, con la coincidencia completa en el índice `0` y algunos detalles adicionales en las propiedades: | ||
cortizg marked this conversation as resolved.
Show resolved
Hide resolved
|
||
```js run | ||
let str = "We will, we will rock you"; | ||
|
||
## Flags | ||
let result = str.match(/we/i); // sin la flag g | ||
cortizg marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
alert( result[0] ); // We (1ra coincidencia) | ||
alert( result.length ); // 1 | ||
|
||
Regular expressions may have flags that affect the search. | ||
// Details: | ||
cortizg marked this conversation as resolved.
Show resolved
Hide resolved
|
||
alert( result.index ); // 0 (posición de la coincidencia) | ||
alert( result.input ); // We will, we will rock you (cadena fuente) | ||
``` | ||
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>. | ||
|
||
There are only 5 of them in JavaScript: | ||
3. Y, finalmente, si no hay coincidencias, se devuelve `null` (no importa si hay una flag `pattern:g` o no). | ||
cortizg marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
`i` | ||
: With this flag the search is case-insensitive: no difference between `A` and `a` (see the example below). | ||
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: | ||
|
||
`g` | ||
: With this flag the search looks for all matches, without it -- only the first one (we'll see uses in the next chapter). | ||
```js run | ||
let matches = "JavaScript".match(/HTML/); // = null | ||
|
||
`m` | ||
: Multiline mode (covered in the chapter <info:regexp-multiline-mode>). | ||
if (!matches.length) { // Error: No se puede leer la propiedad 'length' de null | ||
alert("Error en la línea anterior"); | ||
} | ||
``` | ||
|
||
`s` | ||
: "Dotall" mode, allows `.` to match newlines (covered in the chapter <info:regexp-character-classes>). | ||
Si queremos que el resultado sea siempre un arreglo, podemos escribirlo de esta manera: | ||
|
||
`u` | ||
: Enables full unicode support. The flag enables correct processing of surrogate pairs. More about that in the chapter <info:regexp-unicode>. | ||
```js run | ||
let matches = "JavaScript".match(/HTML/)*!* || []*/!*; | ||
|
||
`y` | ||
: Sticky mode (covered in the chapter <info:regexp-sticky>) | ||
if (!matches.length) { | ||
alert("Sin coincidencias"); // ahora si trabaja | ||
} | ||
``` | ||
|
||
We'll cover all these flags further in the tutorial. | ||
## Reemplazando: str.replace | ||
|
||
For now, the simplest flag is `i`, here's an example: | ||
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 flag `pattern:g`, de lo contrario, solo la primera). | ||
cortizg marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
Por ejemplo: | ||
|
||
```js run | ||
// sin la flag g | ||
cortizg marked this conversation as resolved.
Show resolved
Hide resolved
|
||
alert( "We will, we will".replace(/we/i, "I") ); // I will, we will | ||
|
||
// con la flag g | ||
cortizg marked this conversation as resolved.
Show resolved
Hide resolved
|
||
alert( "We will, we will".replace(/we/ig, "I") ); // I will, I will | ||
``` | ||
|
||
El segundo argumento es la cadena de `reemplazo`. Podemos usar combinaciones de caracteres especiales para insertar fragmentos de la coincidencia: | ||
cortizg marked this conversation as resolved.
Show resolved
Hide resolved
cortizg marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
| Símbolos | Acción en la cadena de reemplazo | | ||
|--------|--------| | ||
|`$&`|inserta toda la coincidencia| | ||
|<code>$`</code>|inserta una parte de la cadena antes de la coincidencia| | ||
|`$'`|inserta una parte de la cadena después de la coincidencia| | ||
|`$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>| | ||
|`$<name>`|inserta el contenido de los paréntesis con el `nombre` dado, más del tema en el capítulo <info:regexp-groups>| | ||
|`$$`|inserta el carácter `$` | | ||
|
||
Un ejemplo con `pattern:$&`: | ||
|
||
```js run | ||
let str = "I love JavaScript!"; | ||
alert( "Me gusta HTML".replace(/HTML/, "$& y JavaScript") ); // Me gusta HTML y JavaScript | ||
``` | ||
|
||
alert( str.search(/LOVE/i) ); // 2 (found lowercased) | ||
## Pruebas: regexp.test | ||
|
||
El método `regexp.test(str)` busca al menos una coincidencia, si se encuentra, devuelve `true`, de lo contrario `false`. | ||
|
||
```js run | ||
let str = "Me gusta JavaScript"; | ||
let regexp = /GUSTA/i; | ||
|
||
alert( str.search(/LOVE/) ); // -1 (nothing found without 'i' flag) | ||
alert( regexp.test(str) ); // true | ||
``` | ||
|
||
So the `i` flag already makes regular expressions more powerful than a simple substring search. But there's so much more. We'll cover other flags and features in the next chapters. | ||
Más adelante en este capítulo estudiaremos más expresiones regulares, exploraremos más ejemplos y también conoceremos otros métodos. | ||
|
||
La información completa sobre métodos se proporciona en el artículo <info:regexp-method>. | ||
|
||
## Summary | ||
## Resumen | ||
|
||
- A regular expression consists of a pattern and optional flags: `g`, `i`, `m`, `u`, `s`, `y`. | ||
- Without flags and special symbols that we'll study later, the search by a regexp is the same as a substring search. | ||
- The method `str.search(regexp)` returns the index where the match is found or `-1` if there's no match. In the next chapter we'll see other methods. | ||
- Una expresión regular consiste en un patrón y flags opcionales: `pattern:g`, `pattern:i`, `pattern:m`, `pattern:u`, `pattern:s`, `pattern:y`. | ||
cortizg marked this conversation as resolved.
Show resolved
Hide resolved
|
||
- Sin flags 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. | ||
cortizg marked this conversation as resolved.
Show resolved
Hide resolved
|
||
- El método `str.match(regexp)` busca coincidencias: devuelve todas si hay una flag `pattern:g`, de lo contrario, solo la primera. | ||
cortizg marked this conversation as resolved.
Show resolved
Hide resolved
|
||
- El método `str.replace(regexp, replacement)` reemplaza las coincidencias encontradas usando `regexp` con `replacement`: devuelve todas si hay una flag `pattern:g`, de lo contrario solo la primera. | ||
cortizg marked this conversation as resolved.
Show resolved
Hide resolved
|
||
- El método `regexp.test(str)` devuelve `true` si hay al menos una coincidencia, de lo contrario, devuelve `false`. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,3 +1,3 @@ | ||
# Regular expressions | ||
# Expresiones Regulares | ||
|
||
Regular expressions is a powerful way of doing search and replace in strings. | ||
Las expresiones regulares son una forma poderosa de hacer búsqueda y reemplazo de cadenas. |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.