Skip to content

Commit ecb8840

Browse files
authored
Merge pull request #424 from mrkrash/regular-expressions/sticky
Sticky flag "y"
2 parents 80c4043 + 298f69e commit ecb8840

File tree

1 file changed

+49
-49
lines changed

1 file changed

+49
-49
lines changed
Lines changed: 49 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -1,55 +1,55 @@
11

2-
# Sticky flag "y", searching at position
2+
# Sticky flag "y", ricerca della posizione
33

4-
The flag `pattern:y` allows to perform the search at the given position in the source string.
4+
Il flag `pattern:y` consente di eseguire la ricerca basata sulla posizione fornita all'interno di una stringa.
55

6-
To grasp the use case of `pattern:y` flag, and better understand the ways of regexps, let's explore a practical example.
6+
Per comprendere il caso d'uso del flag `pattern:y` e comprendere meglio le modalità delle espressioni regolari, esploriamo un esempio pratico.
77

8-
One of common tasks for regexps is "lexical analysis": we get a text, e.g. in a programming language, and need to find its structural elements. For instance, HTML has tags and attributes, JavaScript code has functions, variables, and so on.
8+
Uno dei compiti comuni per le espressioni regolari è "l'analisi lessicale": osserviamo un testo, ad es., in un linguaggio di programmazione, in cui abbiamo bisogno di trovare gli elementi strutturali. Ad esempio, l'HTML ha tag e attributi, il codice JavaScript ha funzioni, variabili e così via.
99

10-
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.
10+
La scrittura di analizzatori lessicali è un ambito particolare, con propri strumenti e algoritmi, quindi non approfondiremo, ma c'è un'attività comune che ci viene incontro: leggere qualcosa a una certa posizione.
1111

12-
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`.
12+
Per esempio, data questa stringa di codice `subject:let varName = "value"`, estraiamo il nome della variabile, che inizia alla posizione `4`.
1313

14-
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.
14+
Proveremo dapprima a cercare il nome della variabile usando una regexp `pattern:\w+`. In realtà, i nomi delle variabili JavaScript richiedono espressioni regolari un po' più complesse per una corrispondenza accurata, ma per il nostro esempio non importa.
1515

16-
- A call to `str.match(/\w+/)` will find only the first word in the line (`let`). That's not it.
17-
- 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.
16+
- Una chiamata a `str.match(/\w+/)` troverà solo la prima parola nella riga (`let`). Non è essa.
17+
- Possiamo aggiungere il flag `pattern:g`. Ma poi la chiamata `str.match(/\w+/g)` cercherà tutte le parole nel testo, mentre abbiamo bisogno di una parola alla posizione `4`. Ancora una volta, non è quello di cui abbiamo bisogno.
1818

19-
**So, how to search for a regexp exactly at the given position?**
19+
**Allora, come effettuiamo una ricerca con una regexp esattamente alla posizione data?**
2020

21-
Let's try using method `regexp.exec(str)`.
21+
Proviamo quindi ad usare il metodo `regexp.exec(str)`.
2222

23-
For a `regexp` without flags `pattern:g` and `pattern:y`, this method looks only for the first match, it works exactly like `str.match(regexp)`.
23+
Questa `regexp`, senza il flag `pattern:g` ne `pattern:y`, troverà solamente la prima corrispondenza, funzionerà esattamente come `str.match(regexp)`.
2424

25-
...But if there's flag `pattern:g`, then it performs the search in `str`, starting from position stored in the `regexp.lastIndex` property. And, if it finds a match, then sets `regexp.lastIndex` to the index immediately after the match.
25+
...Ma se usiamo il flag `pattern:g`, allora verrà effettuata una ricerca in `str`, partendo dalla posizione memorizzata nella proprietà `regexp.lastIndex`. E, se trova una corrispondenza, imposta `regexp.lastIndex` sull'indice immediatamente dopo la corrispondenza.
2626

27-
In other words, `regexp.lastIndex` serves as a starting point for the search, that each `regexp.exec(str)` call resets to the new value ("after the last match"). That's only if there's `pattern:g` flag, of course.
27+
In altre parole, `regexp.lastIndex` serve come punto di partenza per la ricerca, ad ogni chiamata di `regexp.exec(str)` resetta al nuovo valore ("dopo l'ultima corrispondenza"). Questo solo se c'è il flag `pattern:g`, ovviamente.
2828

29-
So, successive calls to `regexp.exec(str)` return matches one after another.
29+
Quindi, chiamate successive a `regexp.exec(str)` ritornano corrispondenze una dopo l'altra.
3030

31-
Here's an example of such calls:
31+
Ecco un esempio di tali chiamate:
3232

3333
```js run
34-
let str = 'let varName'; // Let's find all words in this string
34+
let str = 'let varName'; // Cerchiamo tutte le parole in questa stringa
3535
let regexp = /\w+/g;
3636

37-
alert(regexp.lastIndex); // 0 (initially lastIndex=0)
37+
alert(regexp.lastIndex); // 0 (inizialmente lastIndex=0)
3838

3939
let word1 = regexp.exec(str);
40-
alert(word1[0]); // let (1st word)
41-
alert(regexp.lastIndex); // 3 (position after the match)
40+
alert(word1[0]); // let (1a parola)
41+
alert(regexp.lastIndex); // 3 (posizione dopo la corrispondenza)
4242

4343
let word2 = regexp.exec(str);
44-
alert(word2[0]); // varName (2nd word)
45-
alert(regexp.lastIndex); // 11 (position after the match)
44+
alert(word2[0]); // varName (2a parola)
45+
alert(regexp.lastIndex); // 11 (posizione dopo la corrispondenza)
4646

4747
let word3 = regexp.exec(str);
48-
alert(word3); // null (no more matches)
49-
alert(regexp.lastIndex); // 0 (resets at search end)
48+
alert(word3); // null (non ci sono altre corrispondenze)
49+
alert(regexp.lastIndex); // 0 (resetato dato che la ricerca è terminata)
5050
```
5151

52-
We can get all matches in the loop:
52+
Possiamo quindi individuare tutte le corrispondenze usando un ciclo:
5353

5454
```js run
5555
let str = 'let varName';
@@ -58,24 +58,24 @@ let regexp = /\w+/g;
5858
let result;
5959

6060
while (result = regexp.exec(str)) {
61-
alert( `Found ${result[0]} at position ${result.index}` );
62-
// Found let at position 0, then
63-
// Found varName at position 4
61+
alert( `Trovato ${result[0]} alla posizione ${result.index}` );
62+
// Trovato let alla position 0, quindi
63+
// Trovato varName alla posizione 4
6464
}
6565
```
6666

67-
Such use of `regexp.exec` is an alternative to method `str.matchAll`, with a bit more control over the process.
67+
L'uso di `regexp.exec` è un'alternativa al metodo `str.matchAll`, con un po' più di controllo sul processo.
6868

69-
Let's go back to our task.
69+
Torniamo al nostro compito.
7070

71-
We can manually set `lastIndex` to `4`, to start the search from the given position!
71+
Possiamo impostare manualmente `lastIndex` a `4`, per avviare la ricerca dalla posizione data!
7272

73-
Like this:
73+
Come questo:
7474

7575
```js run
7676
let str = 'let varName = "value"';
7777

78-
let regexp = /\w+/g; // without flag "g", property lastIndex is ignored
78+
let regexp = /\w+/g; // senza flag "g", la proprietà lastIndex è ignorata
7979

8080
*!*
8181
regexp.lastIndex = 4;
@@ -85,54 +85,54 @@ let word = regexp.exec(str);
8585
alert(word); // varName
8686
```
8787

88-
Hooray! Problem solved!
88+
Urrà! Problema risolto!
8989

90-
We performed a search of `pattern:\w+`, starting from position `regexp.lastIndex = 4`.
90+
Abbiamo eseguito una ricerca con `pattern:\w+`, partendo dalla posizione `regexp.lastIndex = 4`.
9191

92-
The result is correct.
92+
Il risultato è corretto.
9393

94-
...But wait, not so fast.
94+
...Ma un attimo, non così in fretta.
9595

96-
Please note: the `regexp.exec` call starts searching 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:
96+
Nota: la chiamata `regexp.exec` inizia la ricerca alla posizione `lastIndex` e poi va oltre. E se non c'è una parola alla posizione `lastIndex`, ma c'è successivamente, allora verrà trovata:
9797

9898
```js run
9999
let str = 'let varName = "value"';
100100

101101
let regexp = /\w+/g;
102102

103103
*!*
104-
// start the search from position 3
104+
// inizia la ricerca dalla posizione 3
105105
regexp.lastIndex = 3;
106106
*/!*
107107

108108
let word = regexp.exec(str);
109-
// found the match at position 4
109+
// trovato la corrispondenza nella posizione 4
110110
alert(word[0]); // varName
111111
alert(word.index); // 4
112112
```
113113

114-
For some tasks, including the lexical analysis, that's just wrong. We need to find a match exactly at the given position at the text, not somewhere after it. And that's what the flag `y` is for.
114+
Per alcune attività, incluse l'analisi lessicale, è semplicemente sbagliato. Dobbiamo trovare una corrispondenza esattamente nella posizione data nel testo, non da qualche parte. Ed è a questo che serve il flag `y`.
115115

116-
**The flag `pattern:y` makes `regexp.exec` to search exactly at position `lastIndex`, not "starting from" it.**
116+
**Il flag `pattern:y` fa in modo che `regexp.exec` cerchi esattamente nella posizione `lastIndex`, non "a partire da" essa**
117117

118-
Here's the same search with flag `pattern:y`:
118+
Ecco la stessa ricerca con il flag `pattern:y`:
119119

120120
```js run
121121
let str = 'let varName = "value"';
122122

123123
let regexp = /\w+/y;
124124

125125
regexp.lastIndex = 3;
126-
alert( regexp.exec(str) ); // null (there's a space at position 3, not a word)
126+
alert( regexp.exec(str) ); // null (c'è uno spazio alla posizione 3, non una parola)
127127

128128
regexp.lastIndex = 4;
129-
alert( regexp.exec(str) ); // varName (word at position 4)
129+
alert( regexp.exec(str) ); // varName (parola nella posizione 4)
130130
```
131131

132-
As we can see, regexp `pattern:/\w+/y` doesn't match at position `3` (unlike the flag `pattern:g`), but matches at position `4`.
132+
Come possiamo notare, la regexp `pattern:/\w+/y` non trova corrispondenze alla posizione `3` (a differenza del flag `pattern:g`), ma trova corrispondenza alla posizione `4`.
133133

134-
Not only that's what we need, there's an important performance gain when using flag `pattern:y`.
134+
Non solo è quello di cui abbiamo bisogno, c'è anche un importante guadagno di prestazioni quando si usa il flag `pattern:y`.
135135

136-
Imagine, we have a long text, and there are no matches in it, at all. Then a search with flag `pattern:g` will go till the end of the text and find nothing, and this will take significantly more time than the search with flag `pattern:y`, that checks only the exact position.
136+
Immaginate, un testo corposo, senza corrispondenze. Quindi una ricerca con il flag `pattern:g` scorrerà tutto il testo senza trovare nulla, e questo richiederà significativamente più tempo della ricerca con il flag `pattern:y`, che controlla solo alla posizione esatta.
137137

138-
In tasks like lexical analysis, there are usually many searches at an exact position, to check what we have there. Using flag `pattern:y` is the key for correct implementations and a good performance.
138+
Nell'analisi lessicale, di solito, si effettuano molte ricerche in base a posizioni esatte, per verificarne il contenuto. L'uso del flag `pattern:y` è la chiave per implementazioni corrette e con buone prestazioni.

0 commit comments

Comments
 (0)