Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

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 ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
vplentinax merged 26 commits intojavascript-tutorial:masterfromcortizg:es.javascript.info.9-01-ri
Jun 11, 2020
Merged
Show file tree
Hide file tree
Changes fromall commits
Commits
Show all changes
26 commits
Select commitHold shift + click to select a range
bf9ca5f
9-01-ri Traducido 18
cortizgJun 9, 2020
cbb314c
Update 9-regular-expressions/01-regexp-introduction/article.md
cortizgJun 10, 2020
f8f5b42
Update 9-regular-expressions/01-regexp-introduction/article.md
cortizgJun 10, 2020
70ef326
Update 9-regular-expressions/01-regexp-introduction/article.md
cortizgJun 10, 2020
d3bc30b
Update 9-regular-expressions/01-regexp-introduction/article.md
cortizgJun 10, 2020
fd70dcd
Update 9-regular-expressions/01-regexp-introduction/article.md
cortizgJun 10, 2020
056e544
Update 9-regular-expressions/01-regexp-introduction/article.md
cortizgJun 10, 2020
5dea5ad
Update 9-regular-expressions/01-regexp-introduction/article.md
cortizgJun 10, 2020
e33ec5b
Update 9-regular-expressions/01-regexp-introduction/article.md
cortizgJun 10, 2020
eba3900
Update 9-regular-expressions/01-regexp-introduction/article.md
cortizgJun 10, 2020
550039e
Update 9-regular-expressions/01-regexp-introduction/article.md
cortizgJun 10, 2020
834ac1a
Update 9-regular-expressions/01-regexp-introduction/article.md
cortizgJun 10, 2020
31afb25
Update 9-regular-expressions/01-regexp-introduction/article.md
cortizgJun 10, 2020
44e59d9
Update 9-regular-expressions/01-regexp-introduction/article.md
cortizgJun 10, 2020
9c34e07
Update 9-regular-expressions/01-regexp-introduction/article.md
cortizgJun 10, 2020
43196a1
Update 9-regular-expressions/01-regexp-introduction/article.md
cortizgJun 10, 2020
b285a9e
Update 9-regular-expressions/01-regexp-introduction/article.md
cortizgJun 10, 2020
d8e9a54
Update 9-regular-expressions/01-regexp-introduction/article.md
cortizgJun 10, 2020
b992920
Update 9-regular-expressions/01-regexp-introduction/article.md
cortizgJun 10, 2020
98c112e
Update 9-regular-expressions/01-regexp-introduction/article.md
cortizgJun 10, 2020
e33144e
Update 9-regular-expressions/01-regexp-introduction/article.md
cortizgJun 10, 2020
ee79bcd
Update 9-regular-expressions/01-regexp-introduction/article.md
cortizgJun 10, 2020
dfab9af
Update 9-regular-expressions/01-regexp-introduction/article.md
cortizgJun 10, 2020
90232f0
Update 9-regular-expressions/01-regexp-introduction/article.md
cortizgJun 10, 2020
769ec75
Merge branch 'master' into es.javascript.info.9-01-ri
cortizgJun 10, 2020
63d4eb5
Update 9-regular-expressions/01-regexp-introduction/article.md
cortizgJun 10, 2020
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
157 changes: 80 additions & 77 deletions9-regular-expressions/01-regexp-introduction/article.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,177 +1,180 @@
#Patterns andflags
#Patrones y banderas (flags)

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

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

##Regular Expressions
##Expresiones Regulares

Aregularexpression (also "regexp",or just "reg")consists of a *pattern* and optional *flags*.
Una expresiónregular(también "regexp",o simplemente "reg")consiste en un *patrón* y *banderas* opcionales.

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

The "long" syntax:
Hay dos sintaxis que se pueden usar para crear un objeto de expresión regular.

La sintaxis "larga":

```js
regexp = new RegExp("pattern", "flags");
regexp = new RegExp("patrón", "banderas");
```

And the "short" one, using slashes `"/"`:
Y el "corto", usando barras `"/"`:

```js
regexp = /pattern/; //no flags
regexp = /pattern/gmi; //with flags g,mand i (to be covered soon)
regexp = /pattern/; //sin banderas
regexp = /pattern/gmi; //con banderas g,me i (para ser cubierto pronto)
```

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

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

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.
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.

Slashes are used when we know theregularexpression 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:
Las barras se utilizan cuando conocemos la expresiónregularen 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
let tag = prompt("What tag do you want to find?", "h2");
let tag = prompt("¿Qué etiqueta quieres encontrar?", "h2");

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

##Flags
##Banderas

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

There are only 6 of them in #"926cb6d766ff6f2ce2eb66157997649afc67b8d81f186206b34ed0b016303e6a">Solo hay 6 de ellas en #"926cb6d766ff6f2ce2eb66157997649afc67b8d81f186206b34ed0b016303e6a">
`pattern:i`
:With this flag the search is case-insensitive: nodifference between`A`and `a` (see the example below).
:Con esta bandera, la búsqueda no distingue entre mayúsculas y minúsculas: nohay diferencia entre`A`y `a` (consulte el ejemplo a continuación).

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

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

`pattern:s`
: Enables "dotall" mode, that allows a dot `pattern:.` to match newline character `\n` (covered in the chapter <info:regexp-character-classes>).
: 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>).


`pattern:u`
:Enables full unicode support. The flag enables correct processing of surrogate pairs. More about that in the chapter <info:regexp-unicode>.
: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>.

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

```smart header="Colors"
From here on the color scheme is:
```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`
```

##Searching: str.match
##Buscando: str.match

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

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

It has 3 working modes:
Tiene 3 modos de trabajo:

1.If theregularexpression has flag `pattern:g`,it returns an array of all matches:
1.Si la expresiónregulartiene la bandera `pattern:g`,devuelve un arreglo de todas las coincidencias:
```js run
let str = "We will, we will rock you";

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

2.If there'snosuch 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:
2.Sinoexiste 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:
```js run
let str = "We will, we will rock you";

let result = str.match(/we/i); //without flag g
let result = str.match(/we/i); //sin la bandera g

alert( result[0] ); // We (1st match)
alert( result[0] ); // We (1ra coincidencia)
alert( result.length ); // 1

//Details:
alert( result.index ); // 0 (position of the match)
alert( result.input ); // We will, we will rock you (source string)
//Detalles:
alert( result.index ); // 0 (posición de la coincidencia)
alert( result.input ); // We will, we will rock you (cadena fuente)
```
The array may have other indexes, besides`0`if a part of theregularexpression is enclosed in parentheses. We'll cover that in the chapter <info:regexp-groups>.
El arreglo puede tener otros índices, además de`0`si una parte de la expresiónregularestá encerrada entre paréntesis. Cubriremos eso en el capítulo <info:regexp-groups>.

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

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

```js run
let matches = "JavaScript".match(/HTML/); // = null

if (!matches.length) { // Error:Cannot read property'length'of null
alert("Errorin the line above");
if (!matches.length) { // Error:No se puede leer la propiedad'length'de null
alert("Erroren la línea anterior");
}
```

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

```js run
let matches = "JavaScript".match(/HTML/)*!* || []*/!*;

if (!matches.length) {
alert("No matches"); //now it works
alert("Sin coincidencias"); //ahora si trabaja
}
```

##Replacing: str.replace
##Reemplazando: str.replace

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).
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).

For instance:
Por ejemplo:

```js run
//no flag g
//sin la bandera g
alert( "We will, we will".replace(/we/i, "I") ); // I will, we will

//with flag g
//con la bandera g
alert( "We will, we will".replace(/we/ig, "I") ); // I will, I will
```

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

|Symbols |Action in the replacement string |
|Símbolos |Acción en la cadena de reemplazo |
|--------|--------|
|`$&`|inserts the whole match|
|<code>$&#096;</code>|inserts a part of the string before the match|
|`$'`|inserts a part of the string after the match|
|`$n`|if `n`is a1-2digit number, then it inserts the contents of n-th parentheses, more about it in the chapter <info:regexp-groups>|
|`$<name>`|inserts the contents of the parentheses with the given `name`, more about it in the chapter <info:regexp-groups>|
|`$$`|inserts character `$` |
|`$&`|inserta toda la coincidencia|
|<code>$&#096;</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 de1-2dí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 `$` |

An example with `pattern:$&`:
Un ejemplo con `pattern:$&`:

```js run
alert( "I love HTML".replace(/HTML/, "$&and JavaScript") ); //I love HTMLand JavaScript
alert( "Me gusta HTML".replace(/HTML/, "$&y JavaScript") ); //Me gusta HTMLy JavaScript
```

##Testing: regexp.test
##Pruebas: regexp.test

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

```js run
let str = "I love JavaScript";
let regexp = /LOVE/i;
let str = "Me gusta JavaScript";
let regexp = /GUSTA/i;


alert( regexp.test(str) ); // true
```

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

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

##Summary
##Resumen

-Aregularexpression consists of a pattern and optional flags: `pattern:g`, `pattern:i`, `pattern:m`, `pattern:u`, `pattern:s`, `pattern: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.match(regexp)`looks for matches: all of them if there's`pattern:g` flag, otherwise, only the first one.
-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.
-The method `regexp.test(str)`returns `true`if there's at least one match, otherwise, it returns `false`.
-Una expresiónregularconsiste en un patrón y banderas opcionales: `pattern:g`, `pattern:i`, `pattern:m`, `pattern:u`, `pattern:s`, `pattern:y`.
-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.
-El método `str.match(regexp)`busca coincidencias: devuelve todas si hay una bandera`pattern:g`, de lo contrario, solo la primera.
-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.
-El método `regexp.test(str)`devuelve `true`si hay al menos una coincidencia, de lo contrario, devuelve `false`.
4 changes: 2 additions & 2 deletions9-regular-expressions/index.md
View file
Open in desktop
Original file line numberDiff line numberDiff 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.

[8]ページ先頭

©2009-2025 Movatter.jp