diff --git a/9-regular-expressions/10-regexp-greedy-and-lazy/1-lazy-greedy/solution.md b/9-regular-expressions/10-regexp-greedy-and-lazy/1-lazy-greedy/solution.md index b8e022223..bc3c2fc45 100644 --- a/9-regular-expressions/10-regexp-greedy-and-lazy/1-lazy-greedy/solution.md +++ b/9-regular-expressions/10-regexp-greedy-and-lazy/1-lazy-greedy/solution.md @@ -1,6 +1,6 @@ -The result is: `match:123 4`. +Il risultato è: `match:123 4`. -First the lazy `pattern:\d+?` tries to take as little digits as it can, but it has to reach the space, so it takes `match:123`. +Inizialmente il quantificatore lazy `pattern:\d+?` prova a prendere il minor numero di cifre, ma deve raggiungere lo spazio, perciò include `match:123`. -Then the second `\d+?` takes only one digit, because that's enough. +Il secondo `\d+?` prende una cifra soltanto perché è sufficiente. diff --git a/9-regular-expressions/10-regexp-greedy-and-lazy/1-lazy-greedy/task.md b/9-regular-expressions/10-regexp-greedy-and-lazy/1-lazy-greedy/task.md index 596f61a4e..18ff849a4 100644 --- a/9-regular-expressions/10-regexp-greedy-and-lazy/1-lazy-greedy/task.md +++ b/9-regular-expressions/10-regexp-greedy-and-lazy/1-lazy-greedy/task.md @@ -1,6 +1,6 @@ -# A match for /d+? d+?/ +# Individuate la corrispondenza per /d+? d+?/ -What's the match here? +Quale è la corrispondenza in questo caso? ```js alert( "123 456".match(/\d+? \d+?/g) ); // ? diff --git a/9-regular-expressions/10-regexp-greedy-and-lazy/3-find-html-comments/solution.md b/9-regular-expressions/10-regexp-greedy-and-lazy/3-find-html-comments/solution.md index 0244963d1..da0ff4a2d 100644 --- a/9-regular-expressions/10-regexp-greedy-and-lazy/3-find-html-comments/solution.md +++ b/9-regular-expressions/10-regexp-greedy-and-lazy/3-find-html-comments/solution.md @@ -1,8 +1,8 @@ -We need to find the beginning of the comment `match:`. +Abbiamo bisogno di trovare l'inizio del commento `match:`. -An acceptable variant is `pattern:` -- the lazy quantifier makes the dot stop right before `match:-->`. We also need to add flag `pattern:s` for the dot to include newlines. +Una variante accettabile è `pattern:`, il quantificatore lazy fa sì che la ricerca si fermi prima di `match:-->`. Dobbiamo, inoltre, aggiungere il flag `pattern:s` in modo che il punto includa gli a capo. -Otherwise multiline comments won't be found: +In caso contrario i commenti multilinea non verranno trovati: ```js run let regexp = //gs; diff --git a/9-regular-expressions/10-regexp-greedy-and-lazy/3-find-html-comments/task.md b/9-regular-expressions/10-regexp-greedy-and-lazy/3-find-html-comments/task.md index 551d9c725..7cd16214b 100644 --- a/9-regular-expressions/10-regexp-greedy-and-lazy/3-find-html-comments/task.md +++ b/9-regular-expressions/10-regexp-greedy-and-lazy/3-find-html-comments/task.md @@ -1,12 +1,12 @@ -# Find HTML comments +# Trovate i commenti HTML -Find all HTML comments in the text: +Trovate tutti i commenti HTML nel testo: ```js let regexp = /your regexp/g; let str = `... .. .. + test --> .. .. `; alert( str.match(regexp) ); // '', '' diff --git a/9-regular-expressions/10-regexp-greedy-and-lazy/4-find-html-tags-greedy-lazy/solution.md b/9-regular-expressions/10-regexp-greedy-and-lazy/4-find-html-tags-greedy-lazy/solution.md index b4d9f7496..b14af98fa 100644 --- a/9-regular-expressions/10-regexp-greedy-and-lazy/4-find-html-tags-greedy-lazy/solution.md +++ b/9-regular-expressions/10-regexp-greedy-and-lazy/4-find-html-tags-greedy-lazy/solution.md @@ -1,5 +1,5 @@ -The solution is `pattern:<[^<>]+>`. +La soluzione è `pattern:<[^<>]+>`. ```js run let regexp = /<[^<>]+>/g; diff --git a/9-regular-expressions/10-regexp-greedy-and-lazy/4-find-html-tags-greedy-lazy/task.md b/9-regular-expressions/10-regexp-greedy-and-lazy/4-find-html-tags-greedy-lazy/task.md index 6759152ff..601b819e9 100644 --- a/9-regular-expressions/10-regexp-greedy-and-lazy/4-find-html-tags-greedy-lazy/task.md +++ b/9-regular-expressions/10-regexp-greedy-and-lazy/4-find-html-tags-greedy-lazy/task.md @@ -1,8 +1,8 @@ -# Find HTML tags +# Trovate i tag HTML -Create a regular expression to find all (opening and closing) HTML tags with their attributes. +Create un'espressione regolare per trovare tutti i tag HTML (di apertura e di chiusura) con i loro attributi. -An example of use: +Ecco un esempio d'uso: ```js run let regexp = /your regexp/g; @@ -12,4 +12,4 @@ let str = '<> '; alert( str.match(regexp) ); // '', '', '' ``` -Here we assume that tag attributes may not contain `<` and `>` (inside quotes too), that simplifies things a bit. +In questo caso presumiamo che gli attributi dei tag non contengano `<` e `>` dentro i doppi apici per semplificare l'esercizio. diff --git a/9-regular-expressions/10-regexp-greedy-and-lazy/article.md b/9-regular-expressions/10-regexp-greedy-and-lazy/article.md index 2f656479d..af976e34b 100644 --- a/9-regular-expressions/10-regexp-greedy-and-lazy/article.md +++ b/9-regular-expressions/10-regexp-greedy-and-lazy/article.md @@ -1,20 +1,20 @@ -# Greedy and lazy quantifiers +# Modalità greedy e lazy dei quantificatori -Quantifiers are very simple from the first sight, but in fact they can be tricky. +I quantificatori sono molto semplici a prima vista, ma in realtà possono rivelarsi complicati. -We should understand how the search works very well if we plan to look for something more complex than `pattern:/\d+/`. +Dovremmo comprendere appieno come funziona la ricerca se intendiamo cercare qualcosa di più complesso di `pattern:/\d+/`. -Let's take the following task as an example. +Prendiamo ad esempio la seguente esercitazione. -We have a text and need to replace all quotes `"..."` with guillemet marks: `«...»`. They are preferred for typography in many countries. +Abbiamo bisogno di rimpiazzare tutti i doppi apici `"..."` in un testo con le virgolette basse: `«...»`, che sono preferite nella tipografia di molti paesi. -For instance: `"Hello, world"` should become `«Hello, world»`. There exist other quotes, such as `„Witam, świat!”` (Polish) or `「你好,世界」` (Chinese), but for our task let's choose `«...»`. +Ad esempio: `"Hello, world"` dovrebbe diventare `«Hello, world»`. Esistono altre virgolette, come `„Witam, świat!”` in Polonia o `「你好,世界」` in Cina, in questo caso, tuttavia, scegliamo `«...»`. -The first thing to do is to locate quoted strings, and then we can replace them. +Innanzitutto dobbiamo individuare le stringhe tra doppi apici per poi sostituirli. -A regular expression like `pattern:/".+"/g` (a quote, then something, then the other quote) may seem like a good fit, but it isn't! +Un'espressione regolare come `pattern:/".+"/g` (una stringa di lunghezza variabile racchiusa da doppi apici) può sembrare efficace, ma non lo è! -Let's try it: +Verifichiamo: ```js run let regexp = /".+"/g; @@ -24,85 +24,85 @@ let str = 'a "witch" and her "broom" is one'; alert( str.match(regexp) ); // "witch" and her "broom" ``` -...We can see that it works not as intended! +Non funziona come desideravamo! -Instead of finding two matches `match:"witch"` and `match:"broom"`, it finds one: `match:"witch" and her "broom"`. +Invece di trovare i due riscontri `match:"witch"` e `match:"broom"`, ne trova solo uno: `match:"witch" and her "broom"`. -That can be described as "greediness is the cause of all evil". +Questo fenomeno può essere descritto così: "l'avidità è la causa di tutti i mali". -## Greedy search +## La ricerca in modalità greedy (avida) -To find a match, the regular expression engine uses the following algorithm: +Per trovare un riscontro, l'interprete dell'espressione regolare usa il seguente algoritmo: -- For every position in the string - - Try to match the pattern at that position. - - If there's no match, go to the next position. +- Per ogni posizione nella stringa + - Cerca un riscontro del pattern in quella posizione. + - Se non c'è un riscontro, passa alla posizione successiva. -These common words do not make it obvious why the regexp fails, so let's elaborate how the search works for the pattern `pattern:".+"`. +Questa procedura generica non ci spiega con evidenza perché l'espressione regolare fallisca, quindi approfondiamo come funziona la ricerca per il pattern `pattern:".+"`. -1. The first pattern character is a quote `pattern:"`. +1. Il primo carattere del pattern è un doppio apice `pattern:"`. - The regular expression engine tries to find it at the zero position of the source string `subject:a "witch" and her "broom" is one`, but there's `subject:a` there, so there's immediately no match. + L'interprete dell'espressione regolare lo cerca alla posizione zero della stringa `subject:a "witch" and her "broom" is one`, ma in quel punto trova `subject:a`, pertanto non c'è immediata corrispondenza. - Then it advances: goes to the next positions in the source string and tries to find the first character of the pattern there, fails again, and finally finds the quote at the 3rd position: + Quindi procede: passa alle successive posizioni nella stringa sorgente e prova a trovare lì il primo carattere del pattern, prima fallisce nuovamente, e poi trova finalmente il doppio apice nella terza posizione: ![](witch_greedy1.svg) -2. The quote is detected, and then the engine tries to find a match for the rest of the pattern. It tries to see if the rest of the subject string conforms to `pattern:.+"`. +2. Rilevato il doppio apice, tenta di trovare riscontro per il resto del pattern. Verifica se il resto della stringa sia conforme a `pattern:.+"`. - In our case the next pattern character is `pattern:.` (a dot). It denotes "any character except a newline", so the next string letter `match:'w'` fits: + Nel nostro esempio il successivo carattere del pattern è `pattern:.` (un punto) che indica "qualsiasi carattere tranne una nuova riga". Trova pertanto corrispondenza nel carattere successivo della stringa `match:'w'`: ![](witch_greedy2.svg) -3. Then the dot repeats because of the quantifier `pattern:.+`. The regular expression engine adds to the match one character after another. +3. Successivamente il punto trova ulteriori riscontri per via del quantificatore `pattern:.+`. L'interprete dell'espressione regolare aggiunge un carattere dopo l'altro. - ...Until when? All characters match the dot, so it only stops when it reaches the end of the string: + Fino a quando? Tutti i caratteri corrispondono al punto, quindi si ferma solo quando raggiunge la fine della stringa: ![](witch_greedy3.svg) -4. Now the engine finished repeating `pattern:.+` and tries to find the next character of the pattern. It's the quote `pattern:"`. But there's a problem: the string has finished, there are no more characters! +4. A questo punto cessa di ripetere `pattern:.+` e prova a trovare il prossimo carattere del pattern. Si tratta del doppio apice `pattern:"`. C'è un problema però: la stringa è finita, non ci sono più caratteri! - The regular expression engine understands that it took too many `pattern:.+` and starts to *backtrack*. + L'interprete dell'espressione regolare capisce di aver preso troppi caratteri per `pattern:.+` e comincia a *retrocedere*. - In other words, it shortens the match for the quantifier by one character: + In altre parole accorcia di un carattere la corrispondenza per il quantificatore: ![](witch_greedy4.svg) - Now it assumes that `pattern:.+` ends one character before the string end and tries to match the rest of the pattern from that position. + A questo punto presume che `pattern:.+` finisca un carattere prima della fine della stringa e verifica la corrispondenza del resto del pattern da quella posizione. - If there were a quote there, then the search would end, but the last character is `subject:'e'`, so there's no match. + Se ci fosse stato un doppio apice, la ricerca sarebbe terminata, ma l'ultima carattere è una `subject:'e'`, nessun riscontro quindi. -5. ...So the engine decreases the number of repetitions of `pattern:.+` by one more character: +5. Allora l'interprete diminuisce di un ulteriore carattere il numero delle ripetizioni di `pattern:.+`: ![](witch_greedy5.svg) - The quote `pattern:'"'` does not match `subject:'n'`. + Anche il carattere `subject:'n'` non soddisfa la ricerca di `pattern:'"'`. -6. The engine keep backtracking: it decreases the count of repetition for `pattern:'.'` until the rest of the pattern (in our case `pattern:'"'`) matches: +6. L'interprete continua a retrocedere: diminuisce le ripetizioni per `pattern:'.'` finché il resto del pattern (nel nostro caso `pattern:'"'`) non trova riscontro: ![](witch_greedy6.svg) -7. The match is complete. +7. La ricerca è completa. -8. So the first match is `match:"witch" and her "broom"`. If the regular expression has flag `pattern:g`, then the search will continue from where the first match ends. There are no more quotes in the rest of the string `subject:is one`, so no more results. +8. Il primo riscontro è quindi `match:"witch" and her "broom"`. Se l'espressione regolare ha il flag `pattern:g`, allora la ricerca proseguirà a partire dalla fine della prima corrispondenza. Non ci sono più doppi apici nel resto della stringa `subject:is one`e, pertanto, non c'è nessun altro risultato. -That's probably not what we expected, but that's how it works. +Probabilmente non è quello che ci aspettavamo, ma funziona così. -**In the greedy mode (by default) a quantified character is repeated as many times as possible.** +**In modalità greedy (quella predefinita) un quantificatore viene ripetuto quante più volte possibile.** -The regexp engine adds to the match as many characters as it can for `pattern:.+`, and then shortens that one by one, if the rest of the pattern doesn't match. +L'interprete della regexp aggiunge quanti più caratteri possibili alla corrispondenza con `pattern:.+`, successivamente retrocede di un carattere alla volta se il resto del pattern non trova riscontro. -For our task we want another thing. That's where a lazy mode can help. +L'obiettivo della nostra esercitazione non è questo, proprio in questi casi viene in soccorso la modalità lazy. -## Lazy mode +## Modalità lazy (pigra) -The lazy mode of quantifiers is an opposite to the greedy mode. It means: "repeat minimal number of times". +La modalità lazy di un quantificatore è l'opposto della modalità greedy. Significa: "ripeti il minor numero di volte". -We can enable it by putting a question mark `pattern:'?'` after the quantifier, so that it becomes `pattern:*?` or `pattern:+?` or even `pattern:??` for `pattern:'?'`. +Possiamo abilitarla mettendo un punto interrogativo `pattern:'?'` dopo il quantificatore, così che diventi `pattern:*?` o `pattern:+?` o ancora `pattern:??` per `pattern:'?'`. -To make things clear: usually a question mark `pattern:?` is a quantifier by itself (zero or one), but if added *after another quantifier (or even itself)* it gets another meaning -- it switches the matching mode from greedy to lazy. +Ricapitoliamo per chiarezza: di norma il punto interrogativo `pattern:?` è di per sé un quantificatore (zero o un carattere), ma se aggiunto *dopo un altro quantificatore (anche dopo se stesso)* assume un altro significato: cambia la modalità di ricerca da greedy a lazy. -The regexp `pattern:/".+?"/g` works as intended: it finds `match:"witch"` and `match:"broom"`: +La regexp `pattern:/".+?"/g` soddisfa le nostre esigenze: trova `match:"witch"` e `match:"broom"`: ```js run let regexp = /".+?"/g; @@ -112,67 +112,67 @@ let str = 'a "witch" and her "broom" is one'; alert( str.match(regexp) ); // "witch", "broom" ``` -To clearly understand the change, let's trace the search step by step. +Per comprendere distintamente cosa sia cambiato, seguiamo la ricerca passo dopo passo. -1. The first step is the same: it finds the pattern start `pattern:'"'` at the 3rd position: +1. Il primo step non cambia: trova l'inizio del pattern `pattern:'"'` nella terza posizione: ![](witch_greedy1.svg) -2. The next step is also similar: the engine finds a match for the dot `pattern:'.'`: +2. Anche il secondo step è simile: l'interprete trova una corrispondenza per il punto `pattern:'.'`: ![](witch_greedy2.svg) -3. And now the search goes differently. Because we have a lazy mode for `pattern:+?`, the engine doesn't try to match a dot one more time, but stops and tries to match the rest of the pattern `pattern:'"'` right now: +3. Da questo punto la ricerca procede in modo differente. Dal momento che il quantificatore è in modalità lazy `pattern:+?`, l'interprete non prova a cercare il punto più di una volta, si ferma e cerca subito la corrispondenza con il resto del pattern `pattern:'"'`: ![](witch_lazy3.svg) - If there were a quote there, then the search would end, but there's `'i'`, so there's no match. -4. Then the regular expression engine increases the number of repetitions for the dot and tries one more time: + Se ci fosse un doppio apice a questo punto la ricerca sarebbe già terminata, ma c'è una `'i'` e quindi nessuna corrispondenza. +4. L'interprete della regexp allora aumenta il numero delle ripetizioni per il punto e riprova: ![](witch_lazy4.svg) - Failure again. Then the number of repetitions is increased again and again... -5. ...Till the match for the rest of the pattern is found: + Ancora nessun risultato. Il numero delle ripetizioni, pertanto, si accresce di volta in volta... +5. ...finché viene riscontrata la corrispondenza con il resto del pattern: ![](witch_lazy5.svg) -6. The next search starts from the end of the current match and yield one more result: +6. La ricerca successiva inizia dalla fine della corrispondenza corrente e produce un altro risultato: ![](witch_lazy6.svg) -In this example we saw how the lazy mode works for `pattern:+?`. Quantifiers `pattern:*?` and `pattern:??` work the similar way -- the regexp engine increases the number of repetitions only if the rest of the pattern can't match on the given position. +In questo esempio abbiamo visto come funziona la modalità lazy per `pattern:+?`. I quantificatori `pattern:*?` e `pattern:??` operano in modo simile: aumentano il numero delle ripetizioni solo se il resto del pattern non ha corrispondenza in una data posizione. -**Laziness is only enabled for the quantifier with `?`.** +**La modalità lazy è abilitata unicamente per il quantificatore seguito da `?`.** -Other quantifiers remain greedy. +Gli altri quantificatori continuano ad operare in modalità greedy. -For instance: +Per esempio: ```js run alert( "123 456".match(/\d+ \d+?/) ); // 123 4 ``` -1. The pattern `pattern:\d+` tries to match as many digits as it can (greedy mode), so it finds `match:123` and stops, because the next character is a space `pattern:' '`. -2. Then there's a space in the pattern, it matches. -3. Then there's `pattern:\d+?`. The quantifier is in lazy mode, so it finds one digit `match:4` and tries to check if the rest of the pattern matches from there. +1. Il pattern `pattern:\d+` cerca quanti più caratteri gli è possibile (modalità greedy), e si ferma quindi dopo aver trovato `match:123`, perché il carattere successivo è una spaziatura `pattern:' '`. +2. Segue la corrispondenza dello spazio nel pattern. +3. A questo punto c'è `pattern:\d+?`. Il quantificatore è modalità lazy, perciò trova solo una cifra `match:4` e prova a verificare se il resto del pattern è soddisfatto. - ...But there's nothing in the pattern after `pattern:\d+?`. + Nel pattern, tuttavia, non c'è niente dopo `pattern:\d+?`. - The lazy mode doesn't repeat anything without a need. The pattern finished, so we're done. We have a match `match:123 4`. + La modalità lazy non ripete nulla se non c'è un motivo. Il pattern è finito e conclude la ricerca. La nostra corrispondenza è `match:123 4`. -```smart header="Optimizations" -Modern regular expression engines can optimize internal algorithms to work faster. So they may work a bit differently from the described algorithm. +```smart header="Ottimizzazioni" +I moderni motori delle regexp possono ottimizzare internamente i loro algoritmi per essere più rapidi. Potrebbero quindi operare in modo leggermente diverso da quanto abbiamo spiegato prima. -But to understand how regular expressions work and to build regular expressions, we don't need to know about that. They are only used internally to optimize things. +Ma per comprendere come funzionino le espressioni regolari e come implementarle non abbiamo bisogno di conoscere questi dettagli. Si tratta di meccanismi interni per ottimizzarne il rendimento. -Complex regular expressions are hard to optimize, so the search may work exactly as described as well. +Del resto è difficile ottimizzare le espressioni regolari complesse, pertanto la ricerca potrebbe anche funzionare esattamente come indicato. ``` -## Alternative approach +## Un approccio alternativo -With regexps, there's often more than one way to do the same thing. +Con le espressioni regolari, spesso abbiamo a disposizione diversi modi di ottenere lo stesso risultato. -In our case we can find quoted strings without lazy mode using the regexp `pattern:"[^"]+"`: +Nel nostro caso potremmo trovare le stringhe tra doppi apici senza la modalità lazy, usando la regexp `pattern:"[^"]+"`: ```js run let regexp = /"[^"]+"/g; @@ -182,120 +182,120 @@ let str = 'a "witch" and her "broom" is one'; alert( str.match(regexp) ); // "witch", "broom" ``` -The regexp `pattern:"[^"]+"` gives correct results, because it looks for a quote `pattern:'"'` followed by one or more non-quotes `pattern:[^"]`, and then the closing quote. +La regexp `pattern:"[^"]+"` restituisce il risultato corretto, perché cerca un doppio apice `pattern:'"'`, seguito da uno o più caratteri che non siano doppi apici `pattern:[^"]` e successivamente un doppio apice di chiusura. -When the regexp engine looks for `pattern:[^"]+` it stops the repetitions when it meets the closing quote, and we're done. +Quando l'interprete della regexp cerca `pattern:[^"]+` si arresta quando incontra il doppio apice di chiusura e termina il suo lavoro. -Please note, that this logic does not replace lazy quantifiers! +Si noti che questa logica non rimpiazza i quantificatori lazy! -It is just different. There are times when we need one or another. +Sono due approcci differenti. Talvolta ci serve uno, a volte l'altro. -**Let's see an example where lazy quantifiers fail and this variant works right.** +**Guardiamo un esempio in cui i quantificatori lazy falliscono e questa variante funziona a dovere.** -For instance, we want to find links of the form ``, with any `href`. +Se volessimo, per esempio, trovare dei link di questo tipo ``, con qualsiasi contenuto per `href`. -Which regular expression to use? +Quale espressione regolare dovremmo usare? -The first idea might be: `pattern://g`. +La prima idea potrebbe essere: `pattern://g`. -Let's check it: +Proviamo: ```js run let str = '......'; let regexp = //g; -// Works! +// Funziona! alert( str.match(regexp) ); // ``` -It worked. But let's see what happens if there are many links in the text? +Ha funzionato. Ma vediamo, cosa succede se ci sono più link nel testo? ```js run let str = '...... ...'; let regexp = //g; -// Whoops! Two links in one match! +// Ops! Due link in una sola corrispondenza! alert( str.match(regexp) ); // ... ``` -Now the result is wrong for the same reason as our "witches" example. The quantifier `pattern:.*` took too many characters. +Il risultato adesso è errato per lo stesso motivo dell'esempio di prima con "witches". Il quantificatore `pattern:.*` ha preso troppi caratteri. -The match looks like this: +Possiamo rappresentare la corrispondenza in questo modo: ```html ... ``` -Let's modify the pattern by making the quantifier `pattern:.*?` lazy: +Modifichiamo allora il pattern rendendo lazy il quantificatore `pattern:.*?`: ```js run let str = '...... ...'; let regexp = //g; -// Works! +// Funziona! alert( str.match(regexp) ); // , ``` -Now it seems to work, there are two matches: +Ora sembra funzionare, ci sono due riscontri: ```html ... ``` -...But let's test it on one more text input: +Ma proviamo ancora su un testo differente: ```js run let str = '......

...'; let regexp = //g; -// Wrong match! +// Corrispondenza errata! alert( str.match(regexp) ); // ...

``` -Now it fails. The match includes not just a link, but also a lot of text after it, including ``. +Ora fallisce. La corrispondenza include non solo il link, ma anche molto altro testo dopo di esso, incluso ``. -Why? +Perché? -That's what's going on: +Ecco quello che sta succedendo: -1. First the regexp finds a link start `match:` (none). -3. Then takes another character into `pattern:.*?`, and so on... until it finally reaches `match:" class="doc">`. +1. Per prima cosa la regexp trova la prima parte del link `match:` (nessuna). +3. Successivamente prende un altro carattere per `pattern:.*?`, e così via...fino al raggiungimento di `match:" class="doc">`. -But the problem is: that's already beyond the link ``, in another tag `

`. Not what we want. +Ma il problema è: quella parte è già al di fuori del link ``, in un altro tag `

`. Non è quello che desideriamo. -Here's the picture of the match aligned with the text: +Ecco la rappresentazione della corrispondenza con il testo allineato: ```html ...

``` -So, we need the pattern to look for ``, but both greedy and lazy variants have problems. +Ricapitoliamo, abbiamo bisogno del pattern per cercare ``, ma entrambe le varianti greedy e lazy danno problemi. -The correct variant can be: `pattern:href="[^"]*"`. It will take all characters inside the `href` attribute till the nearest quote, just what we need. +Un'alternativa corretta potrebbe essere: `pattern:href="[^"]*"`. Essa prenderà tutti i caratteri dentro l'attributo `href` fino al doppio apice più vicino. Proprio quello di cui abbiamo bisogno! -A working example: +Ecco un esempio funzionante: ```js run let str1 = '......

...'; let str2 = '...... ...'; let regexp = //g; -// Works! -alert( str1.match(regexp) ); // null, no matches, that's correct +// Funziona! +alert( str1.match(regexp) ); // null, è corretto che non ci sia alcun riscontro alert( str2.match(regexp) ); // , ``` -## Summary +## Riepilogo -Quantifiers have two modes of work: +I quantificatori possono funzionare in due modalità differenti: Greedy -: By default the regular expression engine tries to repeat the quantified character as many times as possible. For instance, `pattern:\d+` consumes all possible digits. When it becomes impossible to consume more (no more digits or string end), then it continues to match the rest of the pattern. If there's no match then it decreases the number of repetitions (backtracks) and tries again. +: L'interprete delle espressioni regolari, in via predefinita, prova a ripetere un quantificatore quante più volte possibile. Per esempio, `pattern:\d+` considera tutte le cifre disponibili. Quando diventa impossibile trovarne ancora (non ci sono più cifre o è finita la stringa), allora continua a cercare la corrispondenza con il resto del pattern. Se non trova riscontro allora retrocede, diminuisce il numero di ripetizioni e prova ancora. Lazy -: Enabled by the question mark `pattern:?` after the quantifier. The regexp engine tries to match the rest of the pattern before each repetition of the quantified character. +: Abilitata dal punto interrogativo `pattern:?` dopo il quantificatore. L'interprete delle regexp prova la corrispondenza del resto del pattern prima di ogni ripetizione di un carattere quantificato. -As we've seen, the lazy mode is not a "panacea" from the greedy search. An alternative is a "fine-tuned" greedy search, with exclusions, as in the pattern `pattern:"[^"]+"`. +Come abbiamo visto, la modalità lazy non è una "panacea" per i problemi della ricerca greedy. Un'alternativa può essere una ricerca greedy "calibrata", avvalendoci delle esclusioni come nel pattern `pattern:"[^"]+"`.