Scheda riepilogativa delle regex
Un'espressione regolare (regex) è un pattern che cerca testo. Ogni simbolo, detto token, ne cambia il comportamento. La scheda elenca i token più usati, con un significato semplice e un piccolo esempio da copiare e provare.
| Token | Significato | Esempio |
|---|---|---|
| . | Matches any single character except newline. | a.c matches abc, a c |
| * | Matches the preceding token zero or more times. | ab* matches a, abb |
| + | Matches the preceding token one or more times. | ab+ matches ab, abb |
| ? | Makes the preceding token optional (zero or one). | colou?r matches color, colour |
| [] | Character set: matches any one character inside. | [aeiou] matches any vowel |
| [^] | Negated set: matches any character NOT inside. | [^0-9] matches any non-digit |
| \d | Matches any digit (0-9). | \d+ matches 42, 007 |
| \w | Matches any word character (a-z, A-Z, 0-9, _). | \w+ matches hello_1 |
| \s | Matches any whitespace (space, tab, newline). | a\sb matches a b |
| ^ | Anchors the match to the start of a line/string. | ^Hello matches start of string |
| $ | Anchors the match to the end of a line/string. | world$ matches end of string |
| | | Alternation: matches the pattern on either side. | cat|dog matches cat or dog |
| () | Groups a sub-pattern (and captures it). | (ab)+ matches ab, abab |
| {n,m} | Quantifier: match the preceding token n to m times. | a{2,4} matches aa, aaaa |
| (?i) | Inline flag: makes the pattern case-insensitive. | (?i)hello matches HELLO |
Note
- La maggior parte dei token perde il significato speciale dentro un insieme [ ]. Ad esempio, . dentro di [] corrisponde solo a un punto letterale.
- Il backslash (\) è il carattere di escape: rende un token speciale un carattere letterale e viceversa.
- I motori differiscono: Python, JavaScript, PCRE e Golang condividono la maggior parte dei token, ma flag e look-around variano.
Domande frequenti
- Che cosa fa il punto (.) ?
- Per impostazione predefinita il punto corrisponde a qualsiasi carattere eccetto una nuova linea. Per un punto letterale va escapato con \.
- Qual è la differenza tra * e + ?
- L'asterisco * corrisponde al token precedente zero o più volte, quindi 'ab*' corrisponde anche a 'a'. Il più + richiede almeno uno, quindi matcha 'ab' ma non solo 'a'.
- Come corrispondo a una cifra o a un carattere di parola?
- Usa \d per una cifra (0-9) e \w per un carattere di parola (lettere, cifre e underscore). Le negazioni sono \D e \W.
- A cosa servono ^ e $ ?
- ^ aggancia il match all'inizio della stringa o riga; $ alla fine. Insieme, ^pattern$ forza l'intera stringa a corrispondere.