Skip to content

Commit 5944323

Browse files
authored
Merge pull request #424 from AbiF73/master
Sticky flag "y", searching at position
2 parents b29aa56 + 9e57705 commit 5944323

File tree

1 file changed

+38
-41
lines changed

1 file changed

+38
-41
lines changed
Lines changed: 38 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -1,59 +1,56 @@
11

2-
# Sticky flag "y", searching at position
2+
# Indicador adhesivo “y”, buscando en una posición.
33

4-
The flag `pattern:y` allows to perform the search at the given position in the source string.
4+
EL indicador `pattern:y` permite realizar la búsqueda en una posición dada en el string de origen.
55

6-
To grasp the use case of `pattern:y` flag, and see how great it is, let's explore a practical use case.
6+
Para entender el caso de uso del indicador `pattern:y`, y ver lo notable que es, exploremos un ejemplo práctico.
77

8-
One of common tasks for regexps is "lexical analysis": we get a text, e.g. in a programming language, and analyze it for structural elements.
8+
Una tarea común para regexps es el "Análisis léxico": tenemos un texto, por ej. en un lenguaje de programación, y analiza sus elementos estructurales.
99

10-
For instance, HTML has tags and attributes, JavaScript code has functions, variables, and so on.
10+
Por ejemplo, HTML tiene etiquetas y atributos, el código JavaScript tiene funciones, variables, etc.
1111

12-
Writing lexical analyzers is a special area, with its own tools and algorithms, so we don't go deep in there, but there's a common task: to read something at the given position.
12+
Escribir analizadores léxicos es un área especial, con sus propias herramientas y algoritmos, así que no profundizaremos en ello; pero existe una tarea común: leer algo en una posición dada.
1313

14-
E.g. we have a code string `subject:let varName = "value"`, and we need to read the variable name from it, that starts at position `4`.
14+
Por ej. tenemos una cadena de código `subject:let varName = "value"`, y necesitamos leer el nombre de su variable, que comienza en la posición `4`.
1515

16-
We'll look for variable name using regexp `pattern:\w+`. Actually, JavaScript variable names need a bit more complex regexp for accurate matching, but here it doesn't matter.
16+
Buscaremos el nombre de la variable usando regexp `pattern:\w+`. En realidad, el nombre de la variable de JavaScript necesita un regexp un poco más complejo para un emparejamiento más preciso, pero aquí eso no importa.
1717

18-
- A call to `str.match(/\w+/)` will find only the first word in the line (`let`). That's not it.
19-
- We can add the flag `pattern:g`. But then the call `str.match(/\w+/g)` will look for all words in the text, while we need one word at position `4`. Again, not what we need.
18+
Una llamada a `str.match(/\w+/)` solo encontrará la primera palabra de la línea, o todas las palabras con el indicador `pattern:g`. Pero solo necesitamos una palabra en la posición `4`.
2019

21-
**So, how to search for a regexp exactly at the given position?**
20+
Para buscar desde la posición dada, usamos el método `regexp.exec(str)`.
2221

23-
To search from the given position, we can use method `regexp.exec(str)`.
22+
`regexp` no tiene indicadores `pattern:g` o `pattern:y`, entonces este método busca la primera coincidencia en el string `str`, exactamente como `str.match(regexp)`. Un caso tan simple sin indicadores no nos interesa aquí.
2423

25-
If the `regexp` doesn't have flags `pattern:g` or `pattern:y`, then this method looks for the first match in the string `str`, exactly like `str.match(regexp)`. Such simple no-flags case doesn't interest us here.
24+
Si existe el indicador `pattern:g`, realiza la búsqueda en el string `str` empezando desde la posición almacenada en su propiedad `regexp.lastIndex`. Y si encuentra una coincidencia, establece `regexp.lastIndex` en el index inmediatamente después del emparejamiento.
2625

27-
If there's flag `pattern:g`, then it performs the search in the string `str`, starting from position stored in its `regexp.lastIndex` property. And, if it finds a match, then sets `regexp.lastIndex` to the index immediately after the match.
26+
Cuando un regex es creado, su `lastIndex` es `0`.
2827

29-
When a regexp is created, its `lastIndex` is `0`.
28+
Entonces, llamadas sucesivas a `regexp.exec(str)` devuelve coincidencias una después de la otra.
3029

31-
So, successive calls to `regexp.exec(str)` return matches one after another.
32-
33-
An example (with flag `pattern:g`):
30+
Un ejemplo (con el indicador `pattern:g`):
3431

3532
```js run
3633
let str = 'let varName';
3734

3835
let regexp = /\w+/g;
39-
alert(regexp.lastIndex); // 0 (initially lastIndex=0)
36+
alert(regexp.lastIndex); // 0 (inicialmente lastIndex=0)
4037

4138
let word1 = regexp.exec(str);
42-
alert(word1[0]); // let (1st word)
43-
alert(regexp.lastIndex); // 3 (position after the match)
39+
alert(word1[0]); // let (primera palabra)
40+
alert(regexp.lastIndex); // 3 (Posición posterior al emparejamiento)
4441

4542
let word2 = regexp.exec(str);
46-
alert(word2[0]); // varName (2nd word)
47-
alert(regexp.lastIndex); // 11 (position after the match)
43+
alert(word2[0]); // varName (2da palabra)
44+
alert(regexp.lastIndex); // 11 (Posición posterior al emparejamiento)
4845

4946
let word3 = regexp.exec(str);
50-
alert(word3); // null (no more matches)
51-
alert(regexp.lastIndex); // 0 (resets at search end)
47+
alert(word3); // null (no más emparejamientos)
48+
alert(regexp.lastIndex); // 0 (reinicia en el final de la búsqueda)
5249
```
5350

54-
Every match is returned as an array with groups and additional properties.
51+
Cada coincidencia es devuelta como un array con grupos y propiedades adicionales.
5552

56-
We can get all matches in the loop:
53+
Podemos conseguir todas las coincidencias en el loop:
5754

5855
```js run
5956
let str = 'let varName';
@@ -68,16 +65,16 @@ while (result = regexp.exec(str)) {
6865
}
6966
```
7067

71-
Such use of `regexp.exec` is an alternative to method `str.matchAll`.
68+
Tal uso de `regexp.exec` es una alternativa al método `str.match bAll`.
7269

73-
Unlike other methods, we can set our own `lastIndex`, to start the search from the given position.
70+
A diferencia de otros métodos, podemos establecer nuestro propio `lastIndex`, para comenzar la búsqueda desde la posición dada.
7471

75-
For instance, let's find a word, starting from position `4`:
72+
Por ejemplo, encontremos una palabra, comenzando desde la posición `4`:
7673

7774
```js run
7875
let str = 'let varName = "value"';
7976

80-
let regexp = /\w+/g; // without flag "g", property lastIndex is ignored
77+
let regexp = /\w+/g; // Sin el indicador “g”, la propiedad lastindex es ignorada.
8178

8279
*!*
8380
regexp.lastIndex = 4;
@@ -87,9 +84,9 @@ let word = regexp.exec(str);
8784
alert(word); // varName
8885
```
8986

90-
We performed a search of `pattern:\w+`, starting from position `regexp.lastIndex = 4`.
87+
Realizamos una búsqueda de `pattern:\w+`, comenzando desde la posición `regexp.lastIndex = 4`.
9188

92-
Please note: the search starts at position `lastIndex` and then goes further. If there's no word at position `lastIndex`, but it's somewhere after it, then it will be found:
89+
Nota que la búsqueda comienza en la posición `lastIndex` y luego sigue adelante. Si no hay ninguna palabra en la posición `lastIndex` pero la hay en algún lugar posterior, entonces será encontrada:
9390

9491
```js run
9592
let str = 'let varName = "value"';
@@ -105,26 +102,26 @@ alert(word[0]); // varName
105102
alert(word.index); // 4
106103
```
107104

108-
...So, with flag `pattern:g` property `lastIndex` sets the starting position for the search.
105+
...Así que, con la propiedad `lastIndex` del indicador `pattern:g` se establece la posición inicial de la búsqueda.
109106

110-
**Flag `pattern:y` makes `regexp.exec` to look exactly at position `lastIndex`, not before, not after it.**
107+
**El indicador `pattern:y` hace que `regexp.exec` busque exactamente en la posición `lastIndex`, ni antes ni después.**
111108

112-
Here's the same search with flag `pattern:y`:
109+
Aquí está la misma búsqueda con el indicador `pattern:y`:
113110

114111
```js run
115112
let str = 'let varName = "value"';
116113

117114
let regexp = /\w+/y;
118115

119116
regexp.lastIndex = 3;
120-
alert( regexp.exec(str) ); // null (there's a space at position 3, not a word)
117+
alert( regexp.exec(str) ); // null (Hay un espacio en la posición 3, no una palabra)
121118

122119
regexp.lastIndex = 4;
123-
alert( regexp.exec(str) ); // varName (word at position 4)
120+
alert( regexp.exec(str) ); // varName (Una palabra en la posición 4)
124121
```
125122

126-
As we can see, regexp `pattern:/\w+/y` doesn't match at position `3` (unlike the flag `pattern:g`), but matches at position `4`.
123+
Como podemos ver, el `pattern:/\w+/y` de regexp no coincide en la posición `3` (a diferencia del indicador `pattern:g`), pero coincide en la posición `4`.
127124

128-
Imagine, we have a long text, and there are no matches in it, at all. Then searching with flag `pattern:g` will go till the end of the text, and this will take significantly more time than the search with flag `pattern:y`.
125+
Imagina que tenemos un texto largo, y no hay coincidencias en él. Entonces la búsqueda con el indicador `pattern:g` irá hasta el final del texto, y esto tomará significativamente más tiempo que la búsqueda con el indicador `pattern:y`.
129126

130-
In such tasks like lexical analysis, there are usually many searches at an exact position. Using flag `pattern:y` is the key for a good performance.
127+
En tareas tales como el análisis léxico, normalmente hay muchas búsquedas en una posición exacta. Usar el indicador `pattern:y` es la clave para un buen desempeño.

0 commit comments

Comments
 (0)