Skip to content

Commit ffee785

Browse files
authored
Merge pull request #323 from marcellosurdi/article/regexp-alternation
Alternation (OR) |
2 parents 19206e1 + e93c4c9 commit ffee785

File tree

9 files changed

+84
-84
lines changed

9 files changed

+84
-84
lines changed

9-regular-expressions/13-regexp-alternation/01-find-programming-language/solution.md

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11

2-
The first idea can be to list the languages with `|` in-between.
2+
La prima idea potrebbe essere elencare i linguaggi separati da `|`.
33

4-
But that doesn't work right:
4+
Ma non funziona bene:
55

66
```js run
77
let regexp = /Java|JavaScript|PHP|C|C\+\+/g;
@@ -11,18 +11,18 @@ let str = "Java, JavaScript, PHP, C, C++";
1111
alert( str.match(regexp) ); // Java,Java,PHP,C,C
1212
```
1313

14-
The regular expression engine looks for alternations one-by-one. That is: first it checks if we have `match:Java`, otherwise -- looks for `match:JavaScript` and so on.
14+
L'interprete dell'espressione regolare cerca le alternanze una per una. In altre parole: per prima cosa cerca `match:Java`, se non la trova cerca `match:JavaScript` e così via.
1515

16-
As a result, `match:JavaScript` can never be found, just because `match:Java` is checked first.
16+
Il risultato è che `match:JavaScript` non trova mai corrispondenza proprio perché `match:Java` viene controllato per prima.
1717

18-
The same with `match:C` and `match:C++`.
18+
Lo stesso accade con `match:C` e `match:C++`.
1919

20-
There are two solutions for that problem:
20+
Ci sono due soluzioni per questo problema:
2121

22-
1. Change the order to check the longer match first: `pattern:JavaScript|Java|C\+\+|C|PHP`.
23-
2. Merge variants with the same start: `pattern:Java(Script)?|C(\+\+)?|PHP`.
22+
1. Cambiare l'ordine di verifica mettendo per primo il termine più lungo: `pattern:JavaScript|Java|C\+\+|C|PHP`.
23+
2. Unire le varianti che cominciano allo stesso modo: `pattern:Java(Script)?|C(\+\+)?|PHP`.
2424

25-
In action:
25+
In azione:
2626

2727
```js run
2828
let regexp = /Java(Script)?|C(\+\+)?|PHP/g;

9-regular-expressions/13-regexp-alternation/01-find-programming-language/task.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
1-
# Find programming languages
1+
# Trovate il nome dei linguaggi di programmazione
22

3-
There are many programming languages, for instance Java, JavaScript, PHP, C, C++.
3+
Ci sono molti linguaggi di programmazione, Per esempio Java, JavaScript, PHP, C, C++.
44

5-
Create a regexp that finds them in the string `subject:Java JavaScript PHP C++ C`:
5+
Create una regexp che li trovi nella stringa `subject:Java JavaScript PHP C++ C`:
66

77
```js
88
let regexp = /your regexp/g;

9-regular-expressions/13-regexp-alternation/02-find-matching-bbtags/solution.md

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

2-
Opening tag is `pattern:\[(b|url|quote)\]`.
2+
Il tag di apertura è `pattern:\[(b|url|quote)\]`.
33

4-
Then to find everything till the closing tag -- let's use the pattern `pattern:.*?` with flag `pattern:s` to match any character including the newline and then add a backreference to the closing tag.
4+
Successivamente per trovare tutto fino al tag di chiusura usiamo il pattern `pattern:.*?` con il flag `pattern:s` per cercare la corrispondenza con ogni carattere inclusa una nuova riga. Per concludere aggiungiamo un riferimento all'indietro per il tag di chiusura.
55

6-
The full pattern: `pattern:\[(b|url|quote)\].*?\[/\1\]`.
6+
L'intero pattern risultante è: `pattern:\[(b|url|quote)\].*?\[/\1\]`.
77

8-
In action:
8+
In azione:
99

1010
```js run
1111
let regexp = /\[(b|url|quote)\].*?\[\/\1\]/gs;
@@ -20,4 +20,4 @@ let str = `
2020
alert( str.match(regexp) ); // [b]hello![/b],[quote][url]http://google.com[/url][/quote]
2121
```
2222

23-
Please note that besides escaping `pattern:[` and `pattern:]`, we had to escape a slash for the closing tag `pattern:[\/\1]`, because normally the slash closes the pattern.
23+
Si noti che oltre l'escape di `pattern:[` e `pattern:]`, abbiamo dovuto fare l'escape dello slash del tag di chiusura `pattern:[\/\1]`, poiché normalmente lo slash termina il pattern.

9-regular-expressions/13-regexp-alternation/02-find-matching-bbtags/task.md

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,35 +1,35 @@
1-
# Find bbtag pairs
1+
# Trovate le coppie di bbtag
22

3-
A "bb-tag" looks like `[tag]...[/tag]`, where `tag` is one of: `b`, `url` or `quote`.
3+
Un "bb-tag" si presenta così `[tag]...[/tag]`, in cui `tag` è uno tra: `b`, `url` o `quote`.
44

5-
For instance:
5+
Ad esempio:
66
```
77
[b]text[/b]
88
[url]http://google.com[/url]
99
```
1010

11-
BB-tags can be nested. But a tag can't be nested into itself, for instance:
11+
I BB-tags possono essere annidati. Un tag, tuttavia, non può essere contenuto all'interno di uno dello stesso tipo, ad esempio:
1212

1313
```
14-
Normal:
14+
Normale:
1515
[url] [b]http://google.com[/b] [/url]
1616
[quote] [b]text[/b] [/quote]
1717
18-
Can't happen:
18+
Non deve verificarsi:
1919
[b][b]text[/b][/b]
2020
```
2121

22-
Tags can contain line breaks, that's normal:
22+
I tag possono contenere interruzioni di linea, questo è del tutto normale:
2323

2424
```
2525
[quote]
2626
[b]text[/b]
2727
[/quote]
2828
```
2929

30-
Create a regexp to find all BB-tags with their contents.
30+
Create una regexp per trovare tutti i BB-tags con il loro contenuto.
3131

32-
For instance:
32+
Per esempio:
3333

3434
```js
3535
let regexp = /your regexp/flags;
@@ -38,7 +38,7 @@ let str = "..[url]http://google.com[/url]..";
3838
alert( str.match(regexp) ); // [url]http://google.com[/url]
3939
```
4040

41-
If tags are nested, then we need the outer tag (if we want we can continue the search in its content):
41+
In caso di tag annidati ci occorre il tag esterno (se lo desideriamo possiamo continuare la ricerca nel contenuto appena ricavato):
4242

4343
```js
4444
let regexp = /your regexp/flags;

9-regular-expressions/13-regexp-alternation/03-match-quoted-string/solution.md

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
1-
The solution: `pattern:/"(\\.|[^"\\])*"/g`.
1+
La soluzione: `pattern:/"(\\.|[^"\\])*"/g`.
22

3-
Step by step:
3+
Passo dopo passo:
44

5-
- First we look for an opening quote `pattern:"`
6-
- Then if we have a backslash `pattern:\\` (we have to double it in the pattern because it is a special character), then any character is fine after it (a dot).
7-
- Otherwise we take any character except a quote (that would mean the end of the string) and a backslash (to prevent lonely backslashes, the backslash is only used with some other symbol after it): `pattern:[^"\\]`
8-
- ...And so on till the closing quote.
5+
- Innanzitutto cerchiamo un doppio apice di apertura `pattern:"`
6+
- Quindi se abbiamo un backslash `pattern:\\` (dobbiamo raddoppiarlo nel pattern perché è un carattere speciale), qualsiasi carattere dopo di esso è consentito (il punto).
7+
- Altrimenti consideriamo ogni carattere eccetto un doppio apice (che significherebbe la fine della stringa) ed un backslash (per evitare backslashe isolati, il backslash è usato soltanto in congiunzione con altri simboli dopo di esso): `pattern:[^"\\]`
8+
- ...e così via fino al doppio apice di chiusura.
99

10-
In action:
10+
In azione:
1111

1212
```js run
1313
let regexp = /"(\\.|[^"\\])*"/g;
Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,32 @@
1-
# Find quoted strings
1+
# Trovate le stringhe tra doppi apici
22

3-
Create a regexp to find strings in double quotes `subject:"..."`.
3+
Create una regexp per trovare le stringhe tra doppi apici `subject:"..."`.
44

5-
The strings should support escaping, the same way as JavaScript strings do. For instance, quotes can be inserted as `subject:\"` a newline as `subject:\n`, and the slash itself as `subject:\\`.
5+
Le stringhe dovrebbero supportare l'escape allo stesso modo delle stringhe JavaScript. Per esempio, i doppi apici possono essere inseriti come `subject:\"` una nuova linea come `subject:\n`, e lo stesso slash come `subject:\\`.
66

77
```js
88
let str = "Just like \"here\".";
99
```
1010

11-
Please note, in particular, that an escaped quote `subject:\"` does not end a string.
11+
Si noti che, in particolare, un doppio apice con escape `subject:\"` non termina una stringa.
1212

13-
So we should search from one quote to the other ignoring escaped quotes on the way.
13+
Noi dovremmo cercare, pertanto, da un doppio apice fino all'altro ignorando quelli con escape tra i due.
1414

15-
That's the essential part of the task, otherwise it would be trivial.
15+
Questo è la parte fondamentale dell'esercitazione, altrimenti diventerebbe banale.
1616

17-
Examples of strings to match:
17+
Ecco degli esempi di stringhe che corrispondono:
1818
```js
1919
.. *!*"test me"*/!* ..
20-
.. *!*"Say \"Hello\"!"*/!* ... (escaped quotes inside)
21-
.. *!*"\\"*/!* .. (double slash inside)
22-
.. *!*"\\ \""*/!* .. (double slash and an escaped quote inside)
20+
.. *!*"Say \"Hello\"!"*/!* ... (contiene doppi apici con escape)
21+
.. *!*"\\"*/!* .. (contiene un doppio slash)
22+
.. *!*"\\ \""*/!* .. (contiene un doppio slash e un doppio apice con escape)
2323
```
2424

25-
In JavaScript we need to double the slashes to pass them right into the string, like this:
25+
In JavaScript abbiamo bisogno di raddoppiare lo slash per passarli correttamente all'interno della stringa, in questo modo:
2626

2727
```js run
2828
let str = ' .. "test me" .. "Say \\"Hello\\"!" .. "\\\\ \\"" .. ';
2929

30-
// the in-memory string
30+
// la stringa in memoria
3131
alert(str); // .. "test me" .. "Say \"Hello\"!" .. "\\ \"" ..
3232
```

9-regular-expressions/13-regexp-alternation/04-match-exact-tag/solution.md

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
11

2-
The pattern start is obvious: `pattern:<style`.
2+
L'inizio del pattern è ovvio: `pattern:<style`.
33

4-
...But then we can't simply write `pattern:<style.*?>`, because `match:<styler>` would match it.
4+
Ma successivamente non possiamo semplicemente scrivere `pattern:<style.*?>`, poiché altrimenti `match:<styler>` troverebbe corrispondenza.
55

6-
We need either a space after `match:<style` and then optionally something else or the ending `match:>`.
6+
Abbiamo bisogno di uno spazio dopo `match:<style` e dopo facoltativamente qualcos'altro o la `match:>` finale.
77

8-
In the regexp language: `pattern:<style(>|\s.*?>)`.
8+
Tradotto nel linguaggio delle regexp: `pattern:<style(>|\s.*?>)`.
99

10-
In action:
10+
In azione:
1111

1212
```js run
1313
let regexp = /<style(>|\s.*?>)/g;

9-regular-expressions/13-regexp-alternation/04-match-exact-tag/task.md

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
1-
# Find the full tag
1+
# Trovate l'intero tag
22

3-
Write a regexp to find the tag `<style...>`. It should match the full tag: it may have no attributes `<style>` or have several of them `<style type="..." id="...">`.
3+
Scrivete una regexp per trovare il tag `<style...>`. Essa dovrebbe trovare corrispondenza con l'intero tag: esso potrebbe non avere alcun attributo `<style>` o averne diversi `<style type="..." id="...">`.
44

5-
...But the regexp should not match `<styler>`!
5+
La regexp, tuttavia, non dobrebbe accettare `<styler>`!
66

7-
For instance:
7+
Per esempio:
88

99
```js
1010
let regexp = /your regexp/g;

9-regular-expressions/13-regexp-alternation/article.md

Lines changed: 29 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
1-
# Alternation (OR) |
1+
# Alternanza (OR) |
22

3-
Alternation is the term in regular expression that is actually a simple "OR".
3+
Alternanza è un termine usato nelle espressioni regolari che, in realtà, consiste in un semplice "OR".
44

5-
In a regular expression it is denoted with a vertical line character `pattern:|`.
5+
È indicata con un carattere di linea verticale `pattern:|`.
66

7-
For instance, we need to find programming languages: HTML, PHP, Java or JavaScript.
7+
Supponiamo di aver bisogno di trovare il nome di un linguaggio di programmazione: HTML, PHP, Java o JavaScript.
88

9-
The corresponding regexp: `pattern:html|php|java(script)?`.
9+
Ecco la regexp corrispondente: `pattern:html|php|java(script)?`.
1010

11-
A usage example:
11+
Ed ora un esempio d'uso:
1212

1313
```js run
1414
let regexp = /html|php|css|java(script)?/gi;
@@ -18,50 +18,50 @@ let str = "First HTML appeared, then CSS, then JavaScript";
1818
alert( str.match(regexp) ); // 'HTML', 'CSS', 'JavaScript'
1919
```
2020

21-
We already saw a similar thing -- square brackets. They allow to choose between multiple characters, for instance `pattern:gr[ae]y` matches `match:gray` or `match:grey`.
21+
Abbiamo già incontrato una funzionalità simile: le parentesi quadre. Essi permettono di scegliere tra più caratteri, ad esempio `pattern:gr[ae]y` trova corrispondenza con `match:gray` o `match:grey`.
2222

23-
Square brackets allow only characters or character classes. Alternation allows any expressions. A regexp `pattern:A|B|C` means one of expressions `A`, `B` or `C`.
23+
Le parentesi quadre consentono solo caratteri o classi di caratteri. L'alternanza consente qualsiasi espressione. Una regexp `pattern:A|B|C` significa una delle espressioni `A`, `B` o `C`.
2424

25-
For instance:
25+
Per esempio:
2626

27-
- `pattern:gr(a|e)y` means exactly the same as `pattern:gr[ae]y`.
28-
- `pattern:gra|ey` means `match:gra` or `match:ey`.
27+
- `pattern:gr(a|e)y` ha lo stesso identico significato di `pattern:gr[ae]y`.
28+
- `pattern:gra|ey` significa `match:gra` o `match:ey`.
2929

30-
To apply alternation to a chosen part of the pattern, we can enclose it in parentheses:
31-
- `pattern:I love HTML|CSS` matches `match:I love HTML` or `match:CSS`.
32-
- `pattern:I love (HTML|CSS)` matches `match:I love HTML` or `match:I love CSS`.
30+
Per applicare l'alternanza ad una determinata parte di un pattern, dobbiamo racchiuderla tra parentesi:
31+
- `pattern:I love HTML|CSS` trova `match:I love HTML` o `match:CSS`.
32+
- `pattern:I love (HTML|CSS)` corrisponde a `match:I love HTML` o `match:I love CSS`.
3333

34-
## Example: regexp for time
34+
## Esempio: regexp per un orario
3535

36-
In previous articles there was a task to build a regexp for searching time in the form `hh:mm`, for instance `12:00`. But a simple `pattern:\d\d:\d\d` is too vague. It accepts `25:99` as the time (as 99 minutes match the pattern, but that time is invalid).
36+
Negli articoli precedenti abbiamo effettuato un'esercitazione per realizzare una regexp e trovare un orario nel formato `hh:mm`, ad esempio `12:00`. Un semplice `pattern:\d\d:\d\d`, tuttavia, è troppo impreciso. Accetta un orario come `25:99` (poiché 99 minuti trova corrispondenza nel pattern, ma non è un orario valido).
3737

38-
How can we make a better pattern?
38+
Come possiamo migliorare questo pattern?
3939

40-
We can use more careful matching. First, the hours:
40+
Possiamo cercare una corrispondenza più accurata. Per prima cosa, le ore:
4141

42-
- If the first digit is `0` or `1`, then the next digit can be any: `pattern:[01]\d`.
43-
- Otherwise, if the first digit is `2`, then the next must be `pattern:[0-3]`.
44-
- (no other first digit is allowed)
42+
- Se la prima cifra è `0` o `1`, allora la cifra successiva può essere una qualsiasi: `pattern:[01]\d`.
43+
- Diversamente, se la prima cifra è `2`, la successiva deve essere `pattern:[0-3]`.
44+
- Non può esserci un altro carattere come prima cifra.
4545

46-
We can write both variants in a regexp using alternation: `pattern:[01]\d|2[0-3]`.
46+
Possiamo scrivere entrambe le varianti in una regexp usando l'alternanza: `pattern:[01]\d|2[0-3]`.
4747

48-
Next, minutes must be from `00` to `59`. In the regular expression language that can be written as `pattern:[0-5]\d`: the first digit `0-5`, and then any digit.
48+
I minuti a seguire, essi devono essere compresi in un intervallo tra `00` e `59`. In un'espressione regolare ciò può essere reso come `pattern:[0-5]\d`: la prima cifra `0-5`, quindi un numero qualsiasi.
4949

50-
If we glue hours and minutes together, we get the pattern: `pattern:[01]\d|2[0-3]:[0-5]\d`.
50+
Unendo le ore con i minuti otteniamo il pattern seguente: `pattern:[01]\d|2[0-3]:[0-5]\d`.
5151

52-
We're almost done, but there's a problem. The alternation `pattern:|` now happens to be between `pattern:[01]\d` and `pattern:2[0-3]:[0-5]\d`.
52+
Abbiamo quasi finito, ma c'è ancora un problema. L'alternanza `pattern:|` al momento sembra avvenire tra `pattern:[01]\d` e `pattern:2[0-3]:[0-5]\d`.
5353

54-
That is: minutes are added to the second alternation variant, here's a clear picture:
54+
In altre parole: i minuti sono aggiunti al secondo termine dell'alternanza, ecco una rappresentazione più chiara:
5555

5656
```
5757
[01]\d | 2[0-3]:[0-5]\d
5858
```
5959

60-
That pattern looks for `pattern:[01]\d` or `pattern:2[0-3]:[0-5]\d`.
60+
Questo pattern cerca `pattern:[01]\d` o `pattern:2[0-3]:[0-5]\d`.
6161

62-
But that's wrong, the alternation should only be used in the "hours" part of the regular expression, to allow `pattern:[01]\d` OR `pattern:2[0-3]`. Let's correct that by enclosing "hours" into parentheses: `pattern:([01]\d|2[0-3]):[0-5]\d`.
62+
Non è quello che vogliamo, l'alternanza dovrebbe riguardare solo le ore e consentire `pattern:[01]\d` o `pattern:2[0-3]`. Correggiamo racchiudendo le ore tra parentesi: `pattern:([01]\d|2[0-3]):[0-5]\d`.
6363

64-
The final solution:
64+
Ed ecco la soluzione definitiva:
6565

6666
```js run
6767
let regexp = /([01]\d|2[0-3]):[0-5]\d/g;

0 commit comments

Comments
 (0)