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

Capturing groups#345

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
Show file tree
Hide file tree
Changes fromall commits
Commits
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
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,21 @@
A two-digit hex number is`pattern:[0-9a-f]{2}` (assuming the flag`pattern:i` is set).
Un número hexadecimal de dos dígitos es`pattern:[0-9a-f]{2}` (suponiendo que se ha establecido el indicador`pattern:i`).

We need that number`NN`,and then `:NN`repeated 5times (more numbers);
Necesitamos ese número`NN`,y luego `:NN`repetido 5veces (más números);

The regexp is: `pattern:[0-9a-f]{2}(:[0-9a-f]{2}){5}`
La expresión regular es: `pattern:[0-9a-f]{2}(:[0-9a-f]{2}){5}`

Now let's show that the match should capture all the text: start at the beginning and end at the end. That's done by wrapping the pattern in `pattern:^...$`.
Ahora demostremos que la coincidencia debe capturar todo el texto: comience por el principio y termine por el final. Eso se hace envolviendo el patrón en `pattern:^...$`.

Finally:
Finalmente:

```js run
let regexp = /^[0-9a-fA-F]{2}(:[0-9a-fA-F]{2}){5}$/i;

alert( regexp.test('01:32:54:67:89:AB') ); // true

alert( regexp.test('0132546789AB') ); // false (no colons)
alert( regexp.test('0132546789AB') ); // false (sin dos puntos)

alert( regexp.test('01:32:54:67:89') ); // false (5numbers, need 6)
alert( regexp.test('01:32:54:67:89') ); // false (5números, necesita 6)

alert( regexp.test('01:32:54:67:89:ZZ') ) // false (ZZin the end)
alert( regexp.test('01:32:54:67:89:ZZ') ) // false (ZZal final)
```
16 changes: 8 additions & 8 deletions9-regular-expressions/11-regexp-groups/01-test-mac/task.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,20 @@
#CheckMAC-address
#Verificar direcciónMAC

[MAC-address](https://en.wikipedia.org/wiki/MAC_address) of a network interface consists of 6 two-digit hex numbers separated by a colon.
La [DirecciónMAC](https://es.wikipedia.org/wiki/Direcci%C3%B3n_MAC) de una interfaz de red consiste en 6 números hexadecimales de dos dígitos separados por dos puntos.

For instance: `subject:'01:32:54:67:89:AB'`.
Por ejemplo: `subject:'01:32:54:67:89:AB'`.

Write a regexp that checks whether a string isMAC-address.
Escriba una expresión regular que verifique si una cadena es una DirecciónMAC.

Usage:
Uso:
```js
let regexp = /your regexp/;

alert( regexp.test('01:32:54:67:89:AB') ); // true

alert( regexp.test('0132546789AB') ); // false (no colons)
alert( regexp.test('0132546789AB') ); // false (sin dos puntos)

alert( regexp.test('01:32:54:67:89') ); // false (5numbers, must be 6)
alert( regexp.test('01:32:54:67:89') ); // false (5números, necesita 6)

alert( regexp.test('01:32:54:67:89:ZZ') ) // false (ZZad the end)
alert( regexp.test('01:32:54:67:89:ZZ') ) // false (ZZal final)
```
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
A regexp to search 3-digit color `#abc`: `pattern:/#[a-f0-9]{3}/i`.
Una expresión regular para buscar colores de 3 dígitos `#abc`: `pattern:/#[a-f0-9]{3}/i`.

We can add exactly 3 more optional hex digits. We don't need more or less. The colorhas either 3 or 6digits.
Podemos agregar exactamente 3 dígitos hexadecimales opcionales más. No necesitamos más ni menos. El colortiene 3 o 6dígitos.

Let's use the quantifier`pattern:{1,2}`for that: we'll have `pattern:/#([a-f0-9]{3}){1,2}/i`.
Utilizemos el cuantificador`pattern:{1,2}`para esto: llegaremos a `pattern:/#([a-f0-9]{3}){1,2}/i`.

Here the pattern `pattern:[a-f0-9]{3}`is enclosed in parentheses to apply the quantifier `pattern:{1,2}`.
Aquí el patrón `pattern:[a-f0-9]{3}`está rodeado en paréntesis para aplicar el cuantificador `pattern:{1,2}`.

In action:
En acción:

```js run
let regexp = /#([a-f0-9]{3}){1,2}/gi;
Expand All@@ -16,7 +16,7 @@ let str = "color: #3f3; background-color: #AA00ef; and: #abcd";
alert( str.match(regexp) ); // #3f3 #AA00ef #abc
```

There's a minor problem here: the pattern found `match:#abc`in `subject:#abcd`.To prevent that we can add`pattern:\b`to the end:
Hay un pequeño problema aquí: el patrón encontrado `match:#abc`en `subject:#abcd`.Para prevenir esto podemos agregar`pattern:\b`al final:

```js run
let regexp = /#([a-f0-9]{3}){1,2}\b/gi;
Expand Down
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
#Findcolorin the format #abcor #abcdef
#Encuentra elcoloren el formato #abco #abcdef

Write a RegExp that matches colors in the format`#abc`or `#abcdef`.That is: `#`followed by 3or 6hexadecimal digits.
Escriba una expresión regular que haga coincidir los colores en el formato`#abc`o `#abcdef`.Esto es: `#`seguido por 3o 6dígitos hexadecimales.

Usage example:
Ejemplo del uso:
```js
let regexp = /your regexp/g;

Expand All@@ -11,4 +11,4 @@ let str = "color: #3f3; background-color: #AA00ef; and: #abcd";
alert( str.match(regexp) ); // #3f3 #AA00ef
```

P.S. This should be exactly 3or 6hex digits. Values with 4digits, such as `#abcd`,should not match.
P.D. Esto debe ser exactamente 3o 6dígitos hexadecimales. Valores con 4dígitos, tales como `#abcd`,no deben coincidir.
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
A positive number with an optional decimalpart is (per previous task): `pattern:\d+(\.\d+)?`.
Un número positivo con una parte decimalopcional es (de acuerdo a la tarea anterior): `pattern:\d+(\.\d+)?`.

Let's add the optional`pattern:-` in the beginning:
Agreguemos el opcional al comienzo`pattern:-`:

```js run
let regexp = /-?\d+(\.\d+)?/g;
Expand Down
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
#Find all numbers
#Encuentre todos los números

Write a regexp that looks for all decimal numbers including integer ones, with the floating point and negative ones.
Escribe una expresión regular que busque todos los números decimales, incluidos los enteros, con el punto flotante y los negativos.

An example of use:
Un ejemplo de uso:

```js
let regexp = /your regexp/g;
Expand Down
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,44 +1,44 @@
A regexp for a number is: `pattern:-?\d+(\.\d+)?`.We created it in previous tasks.
Una expresión regular para un número es: `pattern:-?\d+(\.\d+)?`.La creamos en tareas anteriores.

An operator is `pattern:[-+*/]`.The hyphen `pattern:-`goes first in the square brackets, because in the middle it would mean a character range, while we just want a character `-`.
Un operador es `pattern:[-+*/]`.El guión `pattern:-`va primero dentro de los corchetes porque colocado en el medio significaría un rango de caracteres, cuando nosotros queremos solamente un carácter `-`.

The slash`/`should be escaped inside a JavaScript regexp`pattern:/.../`,we'll do that later.
La barra inclinada`/`debe ser escapada dentro de una expresión regular de JavaScript`pattern:/.../`,eso lo haremos más tarde.

We need a number, an operator, and then another number. And optional spaces between them.
Necesitamos un número, un operador y luego otro número. Y espacios opcionales entre ellos.

The full regularexpression: `pattern:-?\d+(\.\d+)?\s*[-+*/]\s*-?\d+(\.\d+)?`.
La expresión regularcompleta: `pattern:-?\d+(\.\d+)?\s*[-+*/]\s*-?\d+(\.\d+)?`.

It has 3 parts, with `pattern:\s*`between them:
1. `pattern:-?\d+(\.\d+)?` -the first number,
1. `pattern:[-+*/]` -the operator,
1. `pattern:-?\d+(\.\d+)?` -the second number.
Tiene 3 partes, con `pattern:\s*`en medio de ellas:
1. `pattern:-?\d+(\.\d+)?` -el primer número,
1. `pattern:[-+*/]` -el operador,
1. `pattern:-?\d+(\.\d+)?` -el segundo número.

To make each of these parts a separate element of the resultarray, let's enclose them in parentheses: `pattern:(-?\d+(\.\d+)?)\s*([-+*/])\s*(-?\d+(\.\d+)?)`.
Para hacer que cada una de estas partes sea un elemento separado delarray de resultados, encerrémoslas entre paréntesis: `pattern:(-?\d+(\.\d+)?)\s*([-+*/])\s*(-?\d+(\.\d+)?)`.

In action:
En acción:

```js run
let regexp = /(-?\d+(\.\d+)?)\s*([-+*\/])\s*(-?\d+(\.\d+)?)/;

alert( "1.2 + 12".match(regexp) );
```

The result includes:
El resultado incluye:

- `result[0] == "1.2 + 12"` (full match)
- `result[1] == "1.2"` (first group `(-?\d+(\.\d+)?)` --the first number, including the decimal part)
- `result[2] == ".2"` (second group`(\.\d+)?` --the first decimal part)
- `result[3] == "+"` (third group `([-+*\/])` --the operator)
- `result[4] == "12"` (forth group `(-?\d+(\.\d+)?)` --the second number)
- `result[5] == undefined` (fifth group `(\.\d+)?` --the lastdecimalpart is absent, so it's undefined)
- `result[0] == "1.2 + 12"` (coincidencia completa)
- `result[1] == "1.2"` (primer grupo `(-?\d+(\.\d+)?)` --el primer número, incluyendo la parte decimal)
- `result[2] == ".2"` (segundo grupo`(\.\d+)?` --la primera parte decimal)
- `result[3] == "+"` (tercer grupo `([-+*\/])` --el operador)
- `result[4] == "12"` (cuarto grupo `(-?\d+(\.\d+)?)` --el segundo número)
- `result[5] == undefined` (quinto grupo `(\.\d+)?` --la última partedecimalno está presente, por lo tanto es indefinida)

We only want the numbers and the operator, without the full match or the decimal parts, so let's "clean" the result a bit.
Solo queremos los números y el operador, sin la coincidencia completa o las partes decimales, así que "limpiemos" un poco el resultado.

The full match (the arrays first item) can be removed by shifting the array `result.shift()`.
La coincidencia completa (el primer elemento del array) se puede eliminar cambiando el array `result.shift()`.

Groups that contain decimal parts (number 2and 4) `pattern:(.\d+)`can be excluded by adding `pattern:?:`to the beginning: `pattern:(?:\.\d+)?`.
Los grupos que contengan partes decimales (número 2y 4) `pattern:(.\d+)`pueden ser excluídos al agregar `pattern:?:`al comienzo: `pattern:(?:\.\d+)?`.

The final solution:
La solución final:

```js run
function parse(expr) {
Expand Down
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,23 @@
#Parse an expression
#Analizar una expresión:

An arithmetical expression consists of 2numbers and an operator between them, for instance:
Una expresión aritmética consta de 2números y un operador entre ellos, por ejemplo:

- `1 + 2`
- `1.2 * 3.4`
- `-3 / -6`
- `-2 - 2`

The operator is one of: `"+"`, `"-"`, `"*"`or `"/"`.
El operador es uno de estos: `"+"`, `"-"`, `"*"`o `"/"`.

There may be extra spaces at the beginning, at the end or between the parts.
Puede haber espacios adicionales al principio, al final o entre las partes.

Create a function `parse(expr)`that takes an expression and returns an arrayof 3items:
Crea una función `parse(expr)`que tome una expresión y devuelva un arrayde 3ítems:

1.The first number.
2.The operator.
3.The second number.
1.El primer número.
2.El operador.
3.El segundo número.

For example:
Por ejemplo:

```js
let [a, op, b] = parse("1.2 * 3.4");
Expand Down
Loading

[8]ページ先頭

©2009-2025 Movatter.jp