From 944cf81ec18ad2b96bd4abb77d2a9c25362c4135 Mon Sep 17 00:00:00 2001 From: idrusma Date: Fri, 30 Apr 2021 11:35:39 +0200 Subject: [PATCH 01/11] Starting translation 9-regular-expressions\11-regexp-groups\article --- .../11-regexp-groups/article.md | 90 +++++++++---------- 1 file changed, 45 insertions(+), 45 deletions(-) diff --git a/9-regular-expressions/11-regexp-groups/article.md b/9-regular-expressions/11-regexp-groups/article.md index e0ef00bd3..bb747aac4 100644 --- a/9-regular-expressions/11-regexp-groups/article.md +++ b/9-regular-expressions/11-regexp-groups/article.md @@ -1,31 +1,31 @@ -# Capturing groups +# I gruppi di acquisizione (capturing group) -A part of a pattern can be enclosed in parentheses `pattern:(...)`. This is called a "capturing group". +Una parte del pattern può essere racchiusa tra parentesi `pattern:(...)`, diventando così un "gruppo di acquisizione" (capturing group). -That has two effects: +Ciò comporta due conseguenze: -1. It allows to get a part of the match as a separate item in the result array. -2. If we put a quantifier after the parentheses, it applies to the parentheses as a whole. +1. Possiamo acquisire una parte della corrispondenza come elemento separato all'interno di un array di risultati. +2. Se poniamo un quantificatore dopo le parentesi, questo si applica all'intero gruppo di acquisizione. -## Examples +## Esempi -Let's see how parentheses work in examples. +Vediamo come operano le parentesi attraverso degli esempi. -### Example: gogogo +### Esempio: gogogo -Without parentheses, the pattern `pattern:go+` means `subject:g` character, followed by `subject:o` repeated one or more times. For instance, `match:goooo` or `match:gooooooooo`. +Senza parentesi, il pattern `pattern:go+` significa: il carattere `subject:g` seguito da `subject:o` ripetuto una o più volte. Per esempio `match:goooo` o `match:gooooooooo`. -Parentheses group characters together, so `pattern:(go)+` means `match:go`, `match:gogo`, `match:gogogo` and so on. +Le parentesi raggruppano i caratteri, pertanto `pattern:(go)+` significa `match:go`, `match:gogo`, `match:gogogo` e così via. ```js run alert( 'Gogogo now!'.match(/(go)+/ig) ); // "Gogogo" ``` -### Example: domain +### Esempio: dominio -Let's make something more complex -- a regular expression to search for a website domain. +Facciamo un esempio un po' più complesso, un'espressione regolare per cercare il dominio di un sito. -For example: +Per esempio: ``` mail.com @@ -33,9 +33,9 @@ users.mail.com smith.users.mail.com ``` -As we can see, a domain consists of repeated words, a dot after each one except the last one. +Come possiamo vedere, un dominio consiste in parole ripetute, un punto segue ciascuna parola tranne l'ultima. -In regular expressions that's `pattern:(\w+\.)+\w+`: +Tradotto in un'espressione regolare diventa `pattern:(\w+\.)+\w+`: ```js run let regexp = /(\w+\.)+\w+/g; @@ -43,17 +43,17 @@ let regexp = /(\w+\.)+\w+/g; alert( "site.com my.site.com".match(regexp) ); // site.com,my.site.com ``` -The search works, but the pattern can't match a domain with a hyphen, e.g. `my-site.com`, because the hyphen does not belong to class `pattern:\w`. +La ricerca funziona, ma il pattern non trova riscontro con domini contenenti un trattino, es. `my-site.com`, perché il trattino non appartiene alla classe `pattern:\w`. -We can fix it by replacing `pattern:\w` with `pattern:[\w-]` in every word except the last one: `pattern:([\w-]+\.)+\w+`. +Possiamo correggere il tiro rimpiazzando `pattern:\w` con `pattern:[\w-]` in ogni parola eccetto l'ultima: `pattern:([\w-]+\.)+\w+`. -### Example: email +### Esempio: email -The previous example can be extended. We can create a regular expression for emails based on it. +Il precedente esempio può essere esteso. A partire da questo possiamo creare un'espressione regolare per le email. -The email format is: `name@domain`. Any word can be the name, hyphens and dots are allowed. In regular expressions that's `pattern:[-.\w]+`. +Il formato delle email è: `name@domain`. Qualsiasi parola può essere "name", sono consentiti trattini e punti. L'espressione regolare diventa `pattern:[-.\w]+`. -The pattern: +Ecco il pattern: ```js run let regexp = /[-.\w]+@([\w-]+\.)+[\w-]+/g; @@ -61,24 +61,24 @@ let regexp = /[-.\w]+@([\w-]+\.)+[\w-]+/g; alert("my@mail.com @ his@site.com.uk".match(regexp)); // my@mail.com, his@site.com.uk ``` -That regexp is not perfect, but mostly works and helps to fix accidental mistypes. The only truly reliable check for an email can only be done by sending a letter. +Questa regexp non è perfetta, ma per lo più funziona e aiuta a correggere errori di battitura accidentali. L'unica verifica davvero efficace per un'email può essere fatta soltanto inviandone una. -## Parentheses contents in the match +## I contenuti tra parentesi nella corrispondenza -Parentheses are numbered from left to right. The search engine memorizes the content matched by each of them and allows to get it in the result. +I gruppi tra parentesi sono numerati da sinistra verso destra. Il motore di ricerca memorizza il contenuto associato a ciascuno di essi e consente di recuperarlo nel risultato. -The method `str.match(regexp)`, if `regexp` has no flag `g`, looks for the first match and returns it as an array: +Il metodo `str.match(regexp)`, se `regexp` non ha il flag `g`, cerca la prima corrispondenza e la restituisce in un array: -1. At index `0`: the full match. -2. At index `1`: the contents of the first parentheses. -3. At index `2`: the contents of the second parentheses. -4. ...and so on... +1. Nell'indice `0`: l'intera corrispondenza. +2. Nell'indice `1`: il contenuto del primo gruppo tra parentesi. +3. Nell'indice `2`: il contenuto del secondo. +4. ...e così via... -For instance, we'd like to find HTML tags `pattern:<.*?>`, and process them. It would be convenient to have tag content (what's inside the angles), in a separate variable. +Ad esempio se volessimo trovare i tag HTML `pattern:<.*?>` per elaborarli, sarebbe conveniente averne il contenuto (ciò che è all'interno delle parentesi uncinate) in una variabile separata. -Let's wrap the inner content into parentheses, like this: `pattern:<(.*?)>`. +Racchiudiamo il contenuto tra parentesi, in questo modo: `pattern:<(.*?)>`. -Now we'll get both the tag as a whole `match:

` and its contents `match:h1` in the resulting array: +Adesso otterremo sia l'intero tag `match:

` sia il suo contenuto `match:h1` nell'array di risultati: ```js run let str = '

Hello, world!

'; @@ -89,23 +89,23 @@ alert( tag[0] ); //

alert( tag[1] ); // h1 ``` -### Nested groups +### Gruppi annidati -Parentheses can be nested. In this case the numbering also goes from left to right. +Le parentesi possono essere annidate. Anche in questo caso la numerazione procede da sinistra verso destra. -For instance, when searching a tag in `subject:` we may be interested in: +Per esempio durante la ricerca del tag in `subject:` potrebbe interessarci: -1. The tag content as a whole: `match:span class="my"`. -2. The tag name: `match:span`. -3. The tag attributes: `match:class="my"`. +1. L'intero contenuto del tag: `match:span class="my"`. +2. Il nome del tag: `match:span`. +3. Gli attributi del tag: `match:class="my"`. -Let's add parentheses for them: `pattern:<(([a-z]+)\s*([^>]*))>`. +Aggiungiamo le parentesi per questo scopo: `pattern:<(([a-z]+)\s*([^>]*))>`. -Here's how they are numbered (left to right, by the opening paren): +Ecco come sono numerate (da sinistra verso destra, a partire dalla parentesi di apertura): ![](regexp-nested-groups-pattern.svg) -In action: +In azione: ```js run let str = ''; @@ -119,13 +119,13 @@ alert(result[2]); // span alert(result[3]); // class="my" ``` -The zero index of `result` always holds the full match. +L'indice zero di `result` contiene sempre l'intera corrispondenza. -Then groups, numbered from left to right by an opening paren. The first group is returned as `result[1]`. Here it encloses the whole tag content. +Seguono i gruppi, numerati da sinistra verso destra, a partire dalla parentesi di apertura. Il primo gruppo è `result[1]`, esso racchiude l'intero contenuto del tag. -Then in `result[2]` goes the group from the second opening paren `pattern:([a-z]+)` - tag name, then in `result[3]` the tag: `pattern:([^>]*)`. +Troviamo il gruppo della seconda parentesi `pattern:([a-z]+)` in `result[2]`, a seguire il nome del tag `pattern:([^>]*)` in `result[3]`. -The contents of every group in the string: +Ed ecco la rappresentazione del contenuto di ciascun gruppo nella stringa: ![](regexp-nested-groups-matches.svg) From 9cf483d49d08f63a14b51dd6e3113b005121146d Mon Sep 17 00:00:00 2001 From: Marcello Date: Mon, 3 May 2021 18:14:09 +0200 Subject: [PATCH 02/11] Update 9-regular-expressions\11-regexp-groups\article --- .../11-regexp-groups/article.md | 32 +++++++++---------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/9-regular-expressions/11-regexp-groups/article.md b/9-regular-expressions/11-regexp-groups/article.md index bb747aac4..6ee013e21 100644 --- a/9-regular-expressions/11-regexp-groups/article.md +++ b/9-regular-expressions/11-regexp-groups/article.md @@ -63,7 +63,7 @@ alert("my@mail.com @ his@site.com.uk".match(regexp)); // my@mail.com, his@site.c Questa regexp non è perfetta, ma per lo più funziona e aiuta a correggere errori di battitura accidentali. L'unica verifica davvero efficace per un'email può essere fatta soltanto inviandone una. -## I contenuti tra parentesi nella corrispondenza +## I contenuti tra parentesi della corrispondenza I gruppi tra parentesi sono numerati da sinistra verso destra. Il motore di ricerca memorizza il contenuto associato a ciascuno di essi e consente di recuperarlo nel risultato. @@ -129,44 +129,44 @@ Ed ecco la rappresentazione del contenuto di ciascun gruppo nella stringa: ![](regexp-nested-groups-matches.svg) -### Optional groups +### Gruppi opzionali -Even if a group is optional and doesn't exist in the match (e.g. has the quantifier `pattern:(...)?`), the corresponding `result` array item is present and equals `undefined`. +Anche se un gruppo è opzionale e non ha alcun riscontro (ad esempio ha il quantificatore `pattern:(...)?`), l'elemento corrispondente nell'array `result` è ugualmente presente ed equivale a `undefined`. -For instance, let's consider the regexp `pattern:a(z)?(c)?`. It looks for `"a"` optionally followed by `"z"` optionally followed by `"c"`. +Consideriamo per esempio la regexp `pattern:a(z)?(c)?` che cerca la `"a"` facoltativamente seguita da `"z"` e da `"c"`. -If we run it on the string with a single letter `subject:a`, then the result is: +Se la eseguiamo sulla stringa con la singola lettera `subject:a`, questo è il risultato: ```js run let match = 'a'.match(/a(z)?(c)?/); alert( match.length ); // 3 -alert( match[0] ); // a (whole match) +alert( match[0] ); // a (l'intera corrispondenza) alert( match[1] ); // undefined alert( match[2] ); // undefined ``` -The array has the length of `3`, but all groups are empty. +L'array è costituito da `3` elementi, ma tutti i gruppi sono vuoti. -And here's a more complex match for the string `subject:ac`: +Ed ora ecco un riscontro più articolato per la stringa `subject:ac`: ```js run let match = 'ac'.match(/a(z)?(c)?/) alert( match.length ); // 3 -alert( match[0] ); // ac (whole match) -alert( match[1] ); // undefined, because there's nothing for (z)? +alert( match[0] ); // ac (l'intera corrispondenza) +alert( match[1] ); // undefined, perché non c'è riscontro per (z)? alert( match[2] ); // c ``` -The array length is permanent: `3`. But there's nothing for the group `pattern:(z)?`, so the result is `["ac", undefined, "c"]`. +La lunghezza dell'array resta in ogni caso: `3`, ma non c'è riscontro per il gruppo `pattern:(z)?`, quindi il risultato è `["ac", undefined, "c"]`. -## Searching for all matches with groups: matchAll +## Ricerca di tutte le corrispondenze con gruppi: matchAll -```warn header="`matchAll` is a new method, polyfill may be needed" -The method `matchAll` is not supported in old browsers. +```warn header="`matchAll` è un nuovo metodo, potrebbe essere necessario un polyfill" +Il metodo `matchAll` non è supportato nei browsers più datati. -A polyfill may be required, such as . +Potrebbe essere richiesto un polyfill come . ``` When we search for all matches (flag `pattern:g`), the `match` method does not return contents for groups. @@ -346,7 +346,7 @@ alert( result[1] ); // John alert( result.length ); // 2 (no more items in the array) ``` -## Summary +## Riepilogo Parentheses group together a part of the regular expression, so that the quantifier applies to it as a whole. From f5f458d61f7ebf9120490ab30e02d8af9891b205 Mon Sep 17 00:00:00 2001 From: idrusma Date: Tue, 4 May 2021 08:51:47 +0200 Subject: [PATCH 03/11] Update 9-regular-expressions\11-regexp-groups\article --- .../11-regexp-groups/article.md | 28 +++++++++---------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/9-regular-expressions/11-regexp-groups/article.md b/9-regular-expressions/11-regexp-groups/article.md index 6ee013e21..4f717a554 100644 --- a/9-regular-expressions/11-regexp-groups/article.md +++ b/9-regular-expressions/11-regexp-groups/article.md @@ -169,9 +169,9 @@ Il metodo `matchAll` non è supportato nei browsers più datati. Potrebbe essere richiesto un polyfill come . ``` -When we search for all matches (flag `pattern:g`), the `match` method does not return contents for groups. +Quando cerchiamo tutte le corrispondenze (flag `pattern:g`), il metodo `match` non restituisce il contenuto dei gruppi. -For example, let's find all tags in a string: +Cerchiamo ad esempio tutti i tag in una stringa: ```js run let str = '

'; @@ -181,32 +181,32 @@ let tags = str.match(/<(.*?)>/g); alert( tags ); //

,

``` -The result is an array of matches, but without details about each of them. But in practice we usually need contents of capturing groups in the result. +Il risultato è un array di riscontri, ma senza i dettagli di ciascuno di essi. Nella pratica comune, tuttavia, nel risultato ci occorre il contenuto dei gruppi di acquisizione. -To get them, we should search using the method `str.matchAll(regexp)`. +Per ottenerlo, dovremmo utilizzare la ricerca con il metodo `str.matchAll(regexp)`. -It was added to JavaScript language long after `match`, as its "new and improved version". +È stato aggiunto al linguaggio JavaScript molto tempo dopo `match`, come sua "versione nuova e migliorata". -Just like `match`, it looks for matches, but there are 3 differences: +Proprio come `match` cerca le corrispondenze, ma ci sono 3 differenze: -1. It returns not an array, but an iterable object. -2. When the flag `pattern:g` is present, it returns every match as an array with groups. -3. If there are no matches, it returns not `null`, but an empty iterable object. +1. Non restituisce un array, ma un oggetto iterabile. +2. Quando è presente il flag `pattern:g`, restituisce ogni riscontro come un array i cui elementi corrispondono ai gruppi. +3. Se non c'è alcun riscontro, non restituisce `null`, bensì un oggetto iterabile vuoto. -For instance: +Per esempio: ```js run let results = '

'.matchAll(/<(.*?)>/gi); -// results - is not an array, but an iterable object +// results, non è un array ma un oggetto iterabile alert(results); // [object RegExp String Iterator] alert(results[0]); // undefined (*) -results = Array.from(results); // let's turn it into array +results = Array.from(results); // convertiamolo in un array -alert(results[0]); //

,h1 (1st tag) -alert(results[1]); //

,h2 (2nd tag) +alert(results[0]); //

,h1 (primo tag) +alert(results[1]); //

,h2 (secondo tag) ``` As we can see, the first difference is very important, as demonstrated in the line `(*)`. We can't get the match as `results[0]`, because that object isn't pseudoarray. We can turn it into a real `Array` using `Array.from`. There are more details about pseudoarrays and iterables in the article . From f849660100869f6a22b37eba82c2142d1c41387a Mon Sep 17 00:00:00 2001 From: Marcello Date: Tue, 4 May 2021 17:58:38 +0200 Subject: [PATCH 04/11] 9-regular-expressions\11-regexp-groups\article --- .../11-regexp-groups/article.md | 30 +++++++++---------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/9-regular-expressions/11-regexp-groups/article.md b/9-regular-expressions/11-regexp-groups/article.md index 4f717a554..b6b5f9b3a 100644 --- a/9-regular-expressions/11-regexp-groups/article.md +++ b/9-regular-expressions/11-regexp-groups/article.md @@ -209,27 +209,27 @@ alert(results[0]); //

,h1 (primo tag) alert(results[1]); //

,h2 (secondo tag) ``` -As we can see, the first difference is very important, as demonstrated in the line `(*)`. We can't get the match as `results[0]`, because that object isn't pseudoarray. We can turn it into a real `Array` using `Array.from`. There are more details about pseudoarrays and iterables in the article . +Come possiamo notare la prima differenza è davvero rilevante, lo dimostra la linea `(*)`. Non possiamo ricavare la corrispondenza come `results[0]` perché quell'oggetto non è uno pseudo array. Possiamo convertirlo in un `Array` a tutti gli effetti tramite `Array.from`. Trovate ulteriori dettagli sugli pseudo array e sugli iterabili nell'articolo . -There's no need in `Array.from` if we're looping over results: +Non occorre la conversione con `Array.from` se adoperiamo un ciclo iterativo sui risultati: ```js run let results = '

'.matchAll(/<(.*?)>/gi); for(let result of results) { alert(result); - // first alert:

,h1 - // second:

,h2 + // primo alert:

,h1 + // secondo:

,h2 } ``` -...Or using destructuring: +...Oppure se ci avvaliamo della sintassi destrutturata: ```js let [tag1, tag2] = '

'.matchAll(/<(.*?)>/gi); ``` -Every match, returned by `matchAll`, has the same format as returned by `match` without flag `pattern:g`: it's an array with additional properties `index` (match index in the string) and `input` (source string): +Ogni elemento dell'oggetto di risultati restituito da `matchAll` ha lo stesso formato del risultato di `match` senza il flag `pattern:g`: si tratta di un array con le proprietà aggiuntive `index` (la posizione del riscontro nella stringa) e `input` (la stringa sorgente): ```js run let results = '

'.matchAll(/<(.*?)>/gi); @@ -242,23 +242,23 @@ alert( tag1.index ); // 0 alert( tag1.input ); //

``` -```smart header="Why is a result of `matchAll` an iterable object, not an array?" -Why is the method designed like that? The reason is simple - for the optimization. +```smart header="Perché il risultato di `matchAll` è un oggetto iterabile e non un array?" +Perché questo metodo è progettato in questo modo? La ragione è semplice, per l'ottimizzazione. -The call to `matchAll` does not perform the search. Instead, it returns an iterable object, without the results initially. The search is performed each time we iterate over it, e.g. in the loop. +La chiamata a `matchAll` non esegue la ricerca. Al contrario, restituisce un oggetto iterabile inizialmente privo di risultati. La ricerca è eseguita ogni volta che richiediamo un elemento, ad esempio all'interno di un ciclo iterativo. -So, there will be found as many results as needed, not more. +Verranno pertanto trovati tutti i risultati necessari, non di più. -E.g. there are potentially 100 matches in the text, but in a `for..of` loop we found 5 of them, then decided it's enough and made a `break`. Then the engine won't spend time finding other 95 matches. +Considerate che potrebbero esserci anche 100 riscontri nel testo, ma potremmo decidere che sono sufficienti le prime cinque iterazioni di un ciclo `for..of` e interrompere con `break`. L'interprete a quel punto non sprecherà tempo a recuperare gli altri 95 risultati. ``` -## Named groups +## I gruppi nominati -Remembering groups by their numbers is hard. For simple patterns it's doable, but for more complex ones counting parentheses is inconvenient. We have a much better option: give names to parentheses. +Ricordare i gruppi con i rispettivi numeri è difficoltoso. È fattibile per i pattern semplici, ma per quelli più complessi contare le parentesi è scomodo. Abbiamo a disposizione un'opzione decisamente migliore: dare un nome alle parentesi. -That's done by putting `pattern:?` immediately after the opening paren. +Per farlo inseriamo `pattern:?` subito dopo la parentesi di apertura. -For example, let's look for a date in the format "year-month-day": +Cerchiamo una data, ad esempio, nel formato "year-month-day": ```js run *!* From e01abee685da41606779092471406dc480560172 Mon Sep 17 00:00:00 2001 From: Marcello Date: Tue, 4 May 2021 18:00:42 +0200 Subject: [PATCH 05/11] 9-regular-expressions\11-regexp-groups\article --- .../11-regexp-groups/article.md | 30 +++++++++---------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/9-regular-expressions/11-regexp-groups/article.md b/9-regular-expressions/11-regexp-groups/article.md index 4f717a554..b6b5f9b3a 100644 --- a/9-regular-expressions/11-regexp-groups/article.md +++ b/9-regular-expressions/11-regexp-groups/article.md @@ -209,27 +209,27 @@ alert(results[0]); //

,h1 (primo tag) alert(results[1]); //

,h2 (secondo tag) ``` -As we can see, the first difference is very important, as demonstrated in the line `(*)`. We can't get the match as `results[0]`, because that object isn't pseudoarray. We can turn it into a real `Array` using `Array.from`. There are more details about pseudoarrays and iterables in the article . +Come possiamo notare la prima differenza è davvero rilevante, lo dimostra la linea `(*)`. Non possiamo ricavare la corrispondenza come `results[0]` perché quell'oggetto non è uno pseudo array. Possiamo convertirlo in un `Array` a tutti gli effetti tramite `Array.from`. Trovate ulteriori dettagli sugli pseudo array e sugli iterabili nell'articolo . -There's no need in `Array.from` if we're looping over results: +Non occorre la conversione con `Array.from` se adoperiamo un ciclo iterativo sui risultati: ```js run let results = '

'.matchAll(/<(.*?)>/gi); for(let result of results) { alert(result); - // first alert:

,h1 - // second:

,h2 + // primo alert:

,h1 + // secondo:

,h2 } ``` -...Or using destructuring: +...Oppure se ci avvaliamo della sintassi destrutturata: ```js let [tag1, tag2] = '

'.matchAll(/<(.*?)>/gi); ``` -Every match, returned by `matchAll`, has the same format as returned by `match` without flag `pattern:g`: it's an array with additional properties `index` (match index in the string) and `input` (source string): +Ogni elemento dell'oggetto di risultati restituito da `matchAll` ha lo stesso formato del risultato di `match` senza il flag `pattern:g`: si tratta di un array con le proprietà aggiuntive `index` (la posizione del riscontro nella stringa) e `input` (la stringa sorgente): ```js run let results = '

'.matchAll(/<(.*?)>/gi); @@ -242,23 +242,23 @@ alert( tag1.index ); // 0 alert( tag1.input ); //

``` -```smart header="Why is a result of `matchAll` an iterable object, not an array?" -Why is the method designed like that? The reason is simple - for the optimization. +```smart header="Perché il risultato di `matchAll` è un oggetto iterabile e non un array?" +Perché questo metodo è progettato in questo modo? La ragione è semplice, per l'ottimizzazione. -The call to `matchAll` does not perform the search. Instead, it returns an iterable object, without the results initially. The search is performed each time we iterate over it, e.g. in the loop. +La chiamata a `matchAll` non esegue la ricerca. Al contrario, restituisce un oggetto iterabile inizialmente privo di risultati. La ricerca è eseguita ogni volta che richiediamo un elemento, ad esempio all'interno di un ciclo iterativo. -So, there will be found as many results as needed, not more. +Verranno pertanto trovati tutti i risultati necessari, non di più. -E.g. there are potentially 100 matches in the text, but in a `for..of` loop we found 5 of them, then decided it's enough and made a `break`. Then the engine won't spend time finding other 95 matches. +Considerate che potrebbero esserci anche 100 riscontri nel testo, ma potremmo decidere che sono sufficienti le prime cinque iterazioni di un ciclo `for..of` e interrompere con `break`. L'interprete a quel punto non sprecherà tempo a recuperare gli altri 95 risultati. ``` -## Named groups +## I gruppi nominati -Remembering groups by their numbers is hard. For simple patterns it's doable, but for more complex ones counting parentheses is inconvenient. We have a much better option: give names to parentheses. +Ricordare i gruppi con i rispettivi numeri è difficoltoso. È fattibile per i pattern semplici, ma per quelli più complessi contare le parentesi è scomodo. Abbiamo a disposizione un'opzione decisamente migliore: dare un nome alle parentesi. -That's done by putting `pattern:?` immediately after the opening paren. +Per farlo inseriamo `pattern:?` subito dopo la parentesi di apertura. -For example, let's look for a date in the format "year-month-day": +Cerchiamo una data, ad esempio, nel formato "year-month-day": ```js run *!* From 005e4250174c66a66e2c55039676bf0f556513b1 Mon Sep 17 00:00:00 2001 From: Marcello Date: Tue, 4 May 2021 18:04:16 +0200 Subject: [PATCH 06/11] Update 9-regular-expressions\11-regexp-groups\article --- 9-regular-expressions/11-regexp-groups/article.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/9-regular-expressions/11-regexp-groups/article.md b/9-regular-expressions/11-regexp-groups/article.md index b6b5f9b3a..9887d7f15 100644 --- a/9-regular-expressions/11-regexp-groups/article.md +++ b/9-regular-expressions/11-regexp-groups/article.md @@ -63,7 +63,7 @@ alert("my@mail.com @ his@site.com.uk".match(regexp)); // my@mail.com, his@site.c Questa regexp non è perfetta, ma per lo più funziona e aiuta a correggere errori di battitura accidentali. L'unica verifica davvero efficace per un'email può essere fatta soltanto inviandone una. -## I contenuti tra parentesi della corrispondenza +## I contenuti tra parentesi nella corrispondenza I gruppi tra parentesi sono numerati da sinistra verso destra. Il motore di ricerca memorizza il contenuto associato a ciascuno di essi e consente di recuperarlo nel risultato. From 64a92ec59a5b0057a5b8c56c74ba6738e79408b8 Mon Sep 17 00:00:00 2001 From: idrusma Date: Wed, 5 May 2021 11:26:08 +0200 Subject: [PATCH 07/11] Update 9-regular-expressions\11-regexp-groups\article --- .../11-regexp-groups/article.md | 52 +++++++++---------- 1 file changed, 26 insertions(+), 26 deletions(-) diff --git a/9-regular-expressions/11-regexp-groups/article.md b/9-regular-expressions/11-regexp-groups/article.md index 9887d7f15..0bee66959 100644 --- a/9-regular-expressions/11-regexp-groups/article.md +++ b/9-regular-expressions/11-regexp-groups/article.md @@ -273,11 +273,11 @@ alert(groups.month); // 04 alert(groups.day); // 30 ``` -As you can see, the groups reside in the `.groups` property of the match. +Come potete osservare, troviamo i gruppi dentro la proprietà `.groups`. -To look for all dates, we can add flag `pattern:g`. +Per cercare tutte le date, possiamo aggiungere il flag `pattern:g`. -We'll also need `matchAll` to obtain full matches, together with groups: +Abbiamo inoltre bisogno di `matchAll` per ottenere sia le corrispondenze sia i dettagli dei gruppi: ```js run let dateRegexp = /(?[0-9]{4})-(?[0-9]{2})-(?[0-9]{2})/g; @@ -290,16 +290,16 @@ for(let result of results) { let {year, month, day} = result.groups; alert(`${day}.${month}.${year}`); - // first alert: 30.10.2019 - // second: 01.01.2020 + // primo alert: 30.10.2019 + // secondo: 01.01.2020 } ``` -## Capturing groups in replacement +## Sostituire testo con i gruppi di acquisizione -Method `str.replace(regexp, replacement)` that replaces all matches with `regexp` in `str` allows to use parentheses contents in the `replacement` string. That's done using `pattern:$n`, where `pattern:n` is the group number. +Il metodo `str.replace(regexp, replacement)`, che sostituisce tutti i riscontri con `regexp` in `str`, consente di usare il contenuto tra parentesi nella stringa `replacement`. Per farlo si usa `pattern:$n`, dove `pattern:n` indica il numero del gruppo. -For example, +Ad esempio, ```js run let str = "John Bull"; @@ -308,9 +308,9 @@ let regexp = /(\w+) (\w+)/; alert( str.replace(regexp, '$2, $1') ); // Bull, John ``` -For named parentheses the reference will be `pattern:$`. +Per i gruppi nominati il riferimento sarà `pattern:$`. -For example, let's reformat dates from "year-month-day" to "day.month.year": +Rimoduliamo, ad esempio, le date da "year-month-day" a "day.month.year": ```js run let regexp = /(?[0-9]{4})-(?[0-9]{2})-(?[0-9]{2})/g; @@ -321,44 +321,44 @@ alert( str.replace(regexp, '$.$.$') ); // 30.10.2019, 01.01.2020 ``` -## Non-capturing groups with ?: +## I gruppi non acquisiti e l'uso di ?: -Sometimes we need parentheses to correctly apply a quantifier, but we don't want their contents in results. +Talvolta abbiamo bisogno delle parentesi per applicare correttamente un quantificatore, ma non vogliamo il loro contenuto nel risultato. -A group may be excluded by adding `pattern:?:` in the beginning. +Un gruppo può essere escluso aggiungendo `pattern:?:` all'inizio. -For instance, if we want to find `pattern:(go)+`, but don't want the parentheses contents (`go`) as a separate array item, we can write: `pattern:(?:go)+`. +Se desideriamo, ad esempio, cercare `pattern:(go)+`, ma non vogliamo il contenuto tra le parentesi (`go`) in un elemento dell'array, scriveremo: `pattern:(?:go)+`. -In the example below we only get the name `match:John` as a separate member of the match: +Nell'esempio qui di seguito otterremo solo il nome `match:John` come elemento distinto nel risultato: ```js run let str = "Gogogo John!"; *!* -// ?: exludes 'go' from capturing +// ?: esclude 'go' dall'acquisizione let regexp = /(?:go)+ (\w+)/i; */!* let result = str.match(regexp); -alert( result[0] ); // Gogogo John (full match) +alert( result[0] ); // Gogogo John (l'intera corrispondenza) alert( result[1] ); // John -alert( result.length ); // 2 (no more items in the array) +alert( result.length ); // 2 (non ci sono ulteriori elementi nell'array) ``` ## Riepilogo -Parentheses group together a part of the regular expression, so that the quantifier applies to it as a whole. +Le parentesi raggruppano insieme una parte dell'espressione regolare, in modo che il quantificatore si applichi al gruppo nel suo insieme. -Parentheses groups are numbered left-to-right, and can optionally be named with `(?...)`. +I gruppi tra parentesi sono numerati da sinistra verso destra, e, facoltativamente, si può attribuire loro un nome `(?...)`. -The content, matched by a group, can be obtained in the results: +Il loro contenuto di un gruppo può essere ottenuto nei risultati: -- The method `str.match` returns capturing groups only without flag `pattern:g`. -- The method `str.matchAll` always returns capturing groups. +- Il metodo `str.match` restituisce i gruppi di acquisizione solo se non è presente il flag `pattern:g`. +- Il metodo `str.matchAll` restituisce sempre i gruppi di acquisizione. -If the parentheses have no name, then their contents is available in the match array by its number. Named parentheses are also available in the property `groups`. +Se le parentesi non hanno alcun nome, il loro contenuto è disponibile nell'array dei risultati col loro numero. I gruppi nominati sono disponibili anche nella proprietà `groups`. -We can also use parentheses contents in the replacement string in `str.replace`: by the number `$n` or the name `$`. +Possiamo usare inoltre il contenuto tra parentesi nella sostituzione di stringhe con `str.replace`: in base al numero `$n` o in base al nome `$`. -A group may be excluded from numbering by adding `pattern:?:` in its start. That's used when we need to apply a quantifier to the whole group, but don't want it as a separate item in the results array. We also can't reference such parentheses in the replacement string. +Un gruppo può essere escluso dalla numerazione aggiungendo `pattern:?:` all'inizio. Di solito si fa se abbiamo bisogno di applicare un quantificatore ad un intero gruppo, ma non vogliamo che quel gruppo compaia come elemento distinto nell'array dei risultati. In questo caso non possiamo nemmeno usare un riferimento a tali gruppi nella sostituzione di stringhe. From 2136679212c1f71de06e8b6d5e55c72160331f35 Mon Sep 17 00:00:00 2001 From: Marcello Date: Wed, 5 May 2021 16:49:39 +0200 Subject: [PATCH 08/11] Review 9-regular-expressions\11-regexp-groups\article --- .../11-regexp-groups/article.md | 22 +++++++++---------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/9-regular-expressions/11-regexp-groups/article.md b/9-regular-expressions/11-regexp-groups/article.md index 0bee66959..32c468ab4 100644 --- a/9-regular-expressions/11-regexp-groups/article.md +++ b/9-regular-expressions/11-regexp-groups/article.md @@ -99,7 +99,7 @@ Per esempio durante la ricerca del tag in `subject:` potrebbe i 2. Il nome del tag: `match:span`. 3. Gli attributi del tag: `match:class="my"`. -Aggiungiamo le parentesi per questo scopo: `pattern:<(([a-z]+)\s*([^>]*))>`. +Aggiungiamo le parentesi a questo scopo: `pattern:<(([a-z]+)\s*([^>]*))>`. Ecco come sono numerate (da sinistra verso destra, a partire dalla parentesi di apertura): @@ -123,7 +123,7 @@ L'indice zero di `result` contiene sempre l'intera corrispondenza. Seguono i gruppi, numerati da sinistra verso destra, a partire dalla parentesi di apertura. Il primo gruppo è `result[1]`, esso racchiude l'intero contenuto del tag. -Troviamo il gruppo della seconda parentesi `pattern:([a-z]+)` in `result[2]`, a seguire il nome del tag `pattern:([^>]*)` in `result[3]`. +Troviamo il gruppo della seconda parentesi `pattern:([a-z]+)` in `result[2]` ed a seguire il nome del tag `pattern:([^>]*)` in `result[3]`. Ed ecco la rappresentazione del contenuto di ciascun gruppo nella stringa: @@ -131,7 +131,7 @@ Ed ecco la rappresentazione del contenuto di ciascun gruppo nella stringa: ### Gruppi opzionali -Anche se un gruppo è opzionale e non ha alcun riscontro (ad esempio ha il quantificatore `pattern:(...)?`), l'elemento corrispondente nell'array `result` è ugualmente presente ed equivale a `undefined`. +Anche se un gruppo è opzionale e non ha alcun riscontro (ad esempio ha il quantificatore `pattern:(...)?`), l'elemento corrispondente è comunque presente nell'array `result` ed equivale a `undefined`. Consideriamo per esempio la regexp `pattern:a(z)?(c)?` che cerca la `"a"` facoltativamente seguita da `"z"` e da `"c"`. @@ -164,7 +164,7 @@ La lunghezza dell'array resta in ogni caso: `3`, ma non c'è riscontro per il gr ## Ricerca di tutte le corrispondenze con gruppi: matchAll ```warn header="`matchAll` è un nuovo metodo, potrebbe essere necessario un polyfill" -Il metodo `matchAll` non è supportato nei browsers più datati. +Il metodo `matchAll` non è supportato nei browser più datati. Potrebbe essere richiesto un polyfill come . ``` @@ -277,7 +277,7 @@ Come potete osservare, troviamo i gruppi dentro la proprietà `.groups`. Per cercare tutte le date, possiamo aggiungere il flag `pattern:g`. -Abbiamo inoltre bisogno di `matchAll` per ottenere sia le corrispondenze sia i dettagli dei gruppi: +Abbiamo inoltre bisogno di `matchAll` per ottenere sia le corrispondenze sia il dettaglio dei gruppi: ```js run let dateRegexp = /(?[0-9]{4})-(?[0-9]{2})-(?[0-9]{2})/g; @@ -325,7 +325,7 @@ alert( str.replace(regexp, '$.$.$') ); Talvolta abbiamo bisogno delle parentesi per applicare correttamente un quantificatore, ma non vogliamo il loro contenuto nel risultato. -Un gruppo può essere escluso aggiungendo `pattern:?:` all'inizio. +Un gruppo può essere escluso aggiungendo `pattern:?:` dopo la parentesi di apertura. Se desideriamo, ad esempio, cercare `pattern:(go)+`, ma non vogliamo il contenuto tra le parentesi (`go`) in un elemento dell'array, scriveremo: `pattern:(?:go)+`. @@ -352,13 +352,13 @@ Le parentesi raggruppano insieme una parte dell'espressione regolare, in modo ch I gruppi tra parentesi sono numerati da sinistra verso destra, e, facoltativamente, si può attribuire loro un nome `(?...)`. -Il loro contenuto di un gruppo può essere ottenuto nei risultati: +Il contenuto di un gruppo può essere ottenuto nei risultati: - Il metodo `str.match` restituisce i gruppi di acquisizione solo se non è presente il flag `pattern:g`. -- Il metodo `str.matchAll` restituisce sempre i gruppi di acquisizione. +- Il metodo `str.matchAll` restituisce in ogni caso i gruppi di acquisizione. -Se le parentesi non hanno alcun nome, il loro contenuto è disponibile nell'array dei risultati col loro numero. I gruppi nominati sono disponibili anche nella proprietà `groups`. +Se le parentesi non hanno alcun nome, il loro contenuto è disponibile nell'array dei risultati col rispettivo numero. I gruppi nominati sono disponibili anche nella proprietà `groups`. -Possiamo usare inoltre il contenuto tra parentesi nella sostituzione di stringhe con `str.replace`: in base al numero `$n` o in base al nome `$`. +Possiamo usare, inoltre, il contenuto tra parentesi nella sostituzione di stringhe con `str.replace`: in base al numero `$n` o in base al nome `$`. -Un gruppo può essere escluso dalla numerazione aggiungendo `pattern:?:` all'inizio. Di solito si fa se abbiamo bisogno di applicare un quantificatore ad un intero gruppo, ma non vogliamo che quel gruppo compaia come elemento distinto nell'array dei risultati. In questo caso non possiamo nemmeno usare un riferimento a tali gruppi nella sostituzione di stringhe. +Un gruppo può essere escluso dalla numerazione aggiungendo `pattern:?:` dopo la parentesi di apertura. Di solito si fa se abbiamo bisogno di applicare un quantificatore ad un intero gruppo, ma non vogliamo che quel gruppo compaia come elemento distinto nell'array dei risultati. In quel caso non possiamo nemmeno usare un riferimento a tali gruppi nella sostituzione di stringhe. From 973cbbea9e2a17a804ae1788f77c7ec6ee341a8b Mon Sep 17 00:00:00 2001 From: Marcello Date: Wed, 5 May 2021 17:27:23 +0200 Subject: [PATCH 09/11] Update 9-regular-expressions\11-regexp-groups\01-test-mac\tasks --- .../11-regexp-groups/01-test-mac/solution.md | 16 ++++++++-------- .../11-regexp-groups/01-test-mac/task.md | 2 +- .../02-find-webcolor-3-or-6/solution.md | 12 ++++++------ .../02-find-webcolor-3-or-6/task.md | 8 ++++---- .../03-find-decimal-numbers/solution.md | 4 ++-- .../03-find-decimal-numbers/task.md | 6 +++--- .../04-parse-expression/task.md | 18 +++++++++--------- 7 files changed, 33 insertions(+), 33 deletions(-) diff --git a/9-regular-expressions/11-regexp-groups/01-test-mac/solution.md b/9-regular-expressions/11-regexp-groups/01-test-mac/solution.md index 26f7888f7..7f9b7357c 100644 --- a/9-regular-expressions/11-regexp-groups/01-test-mac/solution.md +++ b/9-regular-expressions/11-regexp-groups/01-test-mac/solution.md @@ -1,21 +1,21 @@ -A two-digit hex number is `pattern:[0-9a-f]{2}` (assuming the flag `pattern:i` is set). +Un numero esadecimale a due cifre è `pattern:[0-9a-f]{2}` (dando per scontato che il flag `pattern:i` sia presente). -We need that number `NN`, and then `:NN` repeated 5 times (more numbers); +Dobbiamo trovare quel numero `NN`, seguito da `:NN` ripetuto 5 volte. -The regexp is: `pattern:[0-9a-f]{2}(:[0-9a-f]{2}){5}` +L'espressione regolare è: `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:^...$`. +Osserviamo, a questo punto, che la corrispondenza dovrebbe catturare tutto il testo: dall'inizio alla fine. A questo scopo racchiudiamo il pattern all'interno di `pattern:^...$`. -Finally: +Quindi: ```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 (non ci sono i due punti) -alert( regexp.test('01:32:54:67:89') ); // false (5 numbers, need 6) +alert( regexp.test('01:32:54:67:89') ); // false (5 numeri invece di 6) -alert( regexp.test('01:32:54:67:89:ZZ') ) // false (ZZ in the end) +alert( regexp.test('01:32:54:67:89:ZZ') ) // false (ZZ alla fine) ``` diff --git a/9-regular-expressions/11-regexp-groups/01-test-mac/task.md b/9-regular-expressions/11-regexp-groups/01-test-mac/task.md index 1ef06fcf9..7cb0fcabe 100644 --- a/9-regular-expressions/11-regexp-groups/01-test-mac/task.md +++ b/9-regular-expressions/11-regexp-groups/01-test-mac/task.md @@ -1,4 +1,4 @@ -# Controllo MAC-address +# Verificate il MAC-address Il [MAC-address](https://it.wikipedia.org/wiki/Indirizzo_MAC) di un'interfaccia di rete è composto da 6 coppie di cifre esadecimali separati dai due punti. diff --git a/9-regular-expressions/11-regexp-groups/02-find-webcolor-3-or-6/solution.md b/9-regular-expressions/11-regexp-groups/02-find-webcolor-3-or-6/solution.md index 0806dc4fd..183fc37d7 100644 --- a/9-regular-expressions/11-regexp-groups/02-find-webcolor-3-or-6/solution.md +++ b/9-regular-expressions/11-regexp-groups/02-find-webcolor-3-or-6/solution.md @@ -1,12 +1,12 @@ -A regexp to search 3-digit color `#abc`: `pattern:/#[a-f0-9]{3}/i`. +L'espressione regolare per cercare un colore di 3 cifre `#abc` è : `pattern:/#[a-f0-9]{3}/i`. -We can add exactly 3 more optional hex digits. We don't need more or less. The color has either 3 or 6 digits. +Possiamo aggiungere esattamente 3 ulteriori cifre esadecimali opzionali. Non abbiamo bisogno di altro. Il colore ha 3 o 6 cifre. -Let's use the quantifier `pattern:{1,2}` for that: we'll have `pattern:/#([a-f0-9]{3}){1,2}/i`. +Usiamo il quantificatore `pattern:{1,2}` a questo scopo: avremo `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}`. +In questo caso il pattern `pattern:[a-f0-9]{3}` è racchiuso tra parentesi per applicare ad esso il quantificatore `pattern:{1,2}`. -In action: +Eccolo in azione: ```js run let regexp = /#([a-f0-9]{3}){1,2}/gi; @@ -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: +C'è un piccolo problema adesso: il pattern `match:#abc` trovato in `subject:#abcd`. Per evitarlo possiamo aggiungere `pattern:\b` alla fine: ```js run let regexp = /#([a-f0-9]{3}){1,2}\b/gi; diff --git a/9-regular-expressions/11-regexp-groups/02-find-webcolor-3-or-6/task.md b/9-regular-expressions/11-regexp-groups/02-find-webcolor-3-or-6/task.md index 09108484a..2f5f821b8 100644 --- a/9-regular-expressions/11-regexp-groups/02-find-webcolor-3-or-6/task.md +++ b/9-regular-expressions/11-regexp-groups/02-find-webcolor-3-or-6/task.md @@ -1,8 +1,8 @@ -# Find color in the format #abc or #abcdef +# Trovate un colore nel formato #abc o #abcdef -Write a RegExp that matches colors in the format `#abc` or `#abcdef`. That is: `#` followed by 3 or 6 hexadecimal digits. +Scrivete un'espressione regolare che trovi i colori nel formato `#abc` o `#abcdef`. In altre parole: `#` seguito da 3 o 6 cifre esadecimali. -Usage example: +Esempio d'uso: ```js let regexp = /your regexp/g; @@ -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 3 or 6 hex digits. Values with 4 digits, such as `#abcd`, should not match. +P.S. Dovrebbe trovare esattamente 3 o 6 cifre esadecimali. I valori con 4 cifre, come `#abcd`, non dovrebbero dar luogo a corrispondenza. diff --git a/9-regular-expressions/11-regexp-groups/03-find-decimal-numbers/solution.md b/9-regular-expressions/11-regexp-groups/03-find-decimal-numbers/solution.md index 813d619ef..48c9c2a66 100644 --- a/9-regular-expressions/11-regexp-groups/03-find-decimal-numbers/solution.md +++ b/9-regular-expressions/11-regexp-groups/03-find-decimal-numbers/solution.md @@ -1,6 +1,6 @@ -A positive number with an optional decimal part is: `pattern:\d+(\.\d+)?`. +Un numero positivo con una parte decimale opzionale è: `pattern:\d+(\.\d+)?`. -Let's add the optional `pattern:-` in the beginning: +Aggiungiamo all'inizio il segno meno facoltativo `pattern:-`: ```js run let regexp = /-?\d+(\.\d+)?/g; diff --git a/9-regular-expressions/11-regexp-groups/03-find-decimal-numbers/task.md b/9-regular-expressions/11-regexp-groups/03-find-decimal-numbers/task.md index 4f5a73fff..18715d187 100644 --- a/9-regular-expressions/11-regexp-groups/03-find-decimal-numbers/task.md +++ b/9-regular-expressions/11-regexp-groups/03-find-decimal-numbers/task.md @@ -1,8 +1,8 @@ -# Find all numbers +# Trovate tutti i numeri -Write a regexp that looks for all decimal numbers including integer ones, with the floating point and negative ones. +Scrivete un'espressione regolare che cerchi tutti i numeri decimali e interi, con virgola mobile e negativi. -An example of use: +Un esempio d'uso: ```js let regexp = /your regexp/g; diff --git a/9-regular-expressions/11-regexp-groups/04-parse-expression/task.md b/9-regular-expressions/11-regexp-groups/04-parse-expression/task.md index 8b54d4683..b166834a9 100644 --- a/9-regular-expressions/11-regexp-groups/04-parse-expression/task.md +++ b/9-regular-expressions/11-regexp-groups/04-parse-expression/task.md @@ -1,23 +1,23 @@ -# Parse an expression +# Analizzate un'espressione -An arithmetical expression consists of 2 numbers and an operator between them, for instance: +Un'espressione aritmetica consiste in 2 numeri e un operatore tra di essi, ad esempio: - `1 + 2` - `1.2 * 3.4` - `-3 / -6` - `-2 - 2` -The operator is one of: `"+"`, `"-"`, `"*"` or `"/"`. +L'operatore è uno fra: `"+"`, `"-"`, `"*"` o `"/"`. -There may be extra spaces at the beginning, at the end or between the parts. +Potrebbero esserci ulteriori spazi all'inizio, alla fine o tra gli elementi. -Create a function `parse(expr)` that takes an expression and returns an array of 3 items: +Create una funzione `parse(expr)` che riceva un'espressione e restituisca un array di 3 elementi: -1. The first number. -2. The operator. -3. The second number. +1. Il primo numero. +2. L'operatore. +3. Il secondo numero. -For example: +Ad esempio: ```js let [a, op, b] = parse("1.2 * 3.4"); From da93e6e7239207f3fcc96e9f2ae30a061e35f109 Mon Sep 17 00:00:00 2001 From: idrusma Date: Fri, 7 May 2021 10:20:11 +0200 Subject: [PATCH 10/11] Update and review 9-regular-expressions\11-regexp-groups\tasks --- .../04-parse-expression/solution.md | 44 +++++++++---------- 1 file changed, 22 insertions(+), 22 deletions(-) diff --git a/9-regular-expressions/11-regexp-groups/04-parse-expression/solution.md b/9-regular-expressions/11-regexp-groups/04-parse-expression/solution.md index ac67519bb..ba87438f0 100644 --- a/9-regular-expressions/11-regexp-groups/04-parse-expression/solution.md +++ b/9-regular-expressions/11-regexp-groups/04-parse-expression/solution.md @@ -1,21 +1,21 @@ -A regexp for a number is: `pattern:-?\d+(\.\d+)?`. We created it in the previous task. +L'espressione regolare per un numero è: `pattern:-?\d+(\.\d+)?`. L'abbiamo creata nell'esercizione precedente. -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 `-`. +Per trovare un operatore usiamo `pattern:[-+*/]`. Il trattino `pattern:-` va posto all'inizio nelle parentesi quadre, in mezzo significherebbe un intervallo di caratteri, mentre noi vogliamo soltanto il carattere `-`. -The slash `/` should be escaped inside a JavaScript regexp `pattern:/.../`, we'll do that later. +Si dovrebbe fare l'escape dello slash `/` dentro una regexp JavaScript `pattern:/.../`, lo faremo dopo. -We need a number, an operator, and then another number. And optional spaces between them. +Abbiamo bisogno di un numero, un operatore, e quindi un altro numero. Tra di essi ci possono essere spazi opzionali. -The full regular expression: `pattern:-?\d+(\.\d+)?\s*[-+*/]\s*-?\d+(\.\d+)?`. +Ecco l'intera espressione regolare: `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. +Questa consta di 3 parti, intervallate da `pattern:\s*`: +1. `pattern:-?\d+(\.\d+)?` - il primo numero, +1. `pattern:[-+*/]` - l'operatore, +1. `pattern:-?\d+(\.\d+)?` - il secondo numero. -To make each of these parts a separate element of the result array, let's enclose them in parentheses: `pattern:(-?\d+(\.\d+)?)\s*([-+*/])\s*(-?\d+(\.\d+)?)`. +Per rendere ciascuna di queste parti un elemento separato dell'array di risultati le racchiudiamo tra parentesi: `pattern:(-?\d+(\.\d+)?)\s*([-+*/])\s*(-?\d+(\.\d+)?)`. -In action: +In azione: ```js run let regexp = /(-?\d+(\.\d+)?)\s*([-+*\/])\s*(-?\d+(\.\d+)?)/; @@ -23,22 +23,22 @@ let regexp = /(-?\d+(\.\d+)?)\s*([-+*\/])\s*(-?\d+(\.\d+)?)/; alert( "1.2 + 12".match(regexp) ); ``` -The result includes: +Il risultato include: -- `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 last decimal part is absent, so it's undefined) +- `result[0] == "1.2 + 12"` (l'intera corrispondenza) +- `result[1] == "1.2"` (il primo gruppo `(-?\d+(\.\d+)?)`, il primo numero compresa la parte decimale) +- `result[2] == ".2"` (il secondo gruppo`(\.\d+)?`, la prima parte decimale) +- `result[3] == "+"` (il terzo gruppo `([-+*\/])`, l'operatore) +- `result[4] == "12"` (il quarto gruppo `(-?\d+(\.\d+)?)`, il secondo numero) +- `result[5] == undefined` (il quinto gruppo `(\.\d+)?`, l'ultima parte decimale è assente, quindi equivale ad undefined) -We only want the numbers and the operator, without the full match or the decimal parts, so let's "clean" the result a bit. +Il nostro scopo è ottenere i numeri e l'operatore, senza l'intera corrispondenza o le parti decimali, quindi "puliamo" un po' il risultato. -The full match (the arrays first item) can be removed by shifting the array `result.shift()`. +L'intera corrispondenza (il primo elemento dell'array) possiamo rimuoverla con `result.shift()`. -Groups that contain decimal parts (number 2 and 4) `pattern:(.\d+)` can be excluded by adding `pattern:?:` to the beginning: `pattern:(?:\.\d+)?`. +I gruppi che contengono le parti decimali (gli elementi 2 e 4) `pattern:(.\d+)` li escludiamo aggiungendo `pattern:?:` all'inizio: `pattern:(?:\.\d+)?`. -The final solution: +La soluzione finale: ```js run function parse(expr) { From b0087136e7c1d933e9b461663f8e414b6ce632d0 Mon Sep 17 00:00:00 2001 From: marcellosurdi <42266628+marcellosurdi@users.noreply.github.com> Date: Sat, 15 May 2021 11:21:30 +0200 Subject: [PATCH 11/11] Apply suggestions from code review Co-authored-by: Andrea <45577511+longo-andrea@users.noreply.github.com> --- .../11-regexp-groups/02-find-webcolor-3-or-6/solution.md | 4 ++-- .../11-regexp-groups/04-parse-expression/solution.md | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/9-regular-expressions/11-regexp-groups/02-find-webcolor-3-or-6/solution.md b/9-regular-expressions/11-regexp-groups/02-find-webcolor-3-or-6/solution.md index 183fc37d7..dbf6234e8 100644 --- a/9-regular-expressions/11-regexp-groups/02-find-webcolor-3-or-6/solution.md +++ b/9-regular-expressions/11-regexp-groups/02-find-webcolor-3-or-6/solution.md @@ -1,6 +1,6 @@ -L'espressione regolare per cercare un colore di 3 cifre `#abc` è : `pattern:/#[a-f0-9]{3}/i`. +L'espressione regolare per cercare il codice di un colore di 3 cifre `#abc` è : `pattern:/#[a-f0-9]{3}/i`. -Possiamo aggiungere esattamente 3 ulteriori cifre esadecimali opzionali. Non abbiamo bisogno di altro. Il colore ha 3 o 6 cifre. +Possiamo aggiungere esattamente 3 ulteriori cifre esadecimali opzionali. Non abbiamo bisogno di altro. Il codice di un colore è composto da 3 o 6 cifre. Usiamo il quantificatore `pattern:{1,2}` a questo scopo: avremo `pattern:/#([a-f0-9]{3}){1,2}/i`. diff --git a/9-regular-expressions/11-regexp-groups/04-parse-expression/solution.md b/9-regular-expressions/11-regexp-groups/04-parse-expression/solution.md index ba87438f0..81282e8b3 100644 --- a/9-regular-expressions/11-regexp-groups/04-parse-expression/solution.md +++ b/9-regular-expressions/11-regexp-groups/04-parse-expression/solution.md @@ -2,7 +2,7 @@ L'espressione regolare per un numero è: `pattern:-?\d+(\.\d+)?`. L'abbiamo crea Per trovare un operatore usiamo `pattern:[-+*/]`. Il trattino `pattern:-` va posto all'inizio nelle parentesi quadre, in mezzo significherebbe un intervallo di caratteri, mentre noi vogliamo soltanto il carattere `-`. -Si dovrebbe fare l'escape dello slash `/` dentro una regexp JavaScript `pattern:/.../`, lo faremo dopo. +Dovremmo fare l'escape dello slash `/` dentro una regexp JavaScript `pattern:/.../`, lo faremo dopo. Abbiamo bisogno di un numero, un operatore, e quindi un altro numero. Tra di essi ci possono essere spazi opzionali. pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy