Aide-mémoire des expressions régulières
Une expression régulière (regex) est un motif qui cherche du texte. Chaque symbole, appelé token, modifie le comportement du motif. La fiche ci-dessous liste les tokens les plus utiles, avec leur sens en langage clair et un petit exemple à copier et tester.
| Token | Signification | Exemple |
|---|---|---|
| . | 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 |
Notes
- La plupart des tokens perdent leur sens spécial à l'intérieur d'une classe [ ]. Par exemple, . dans [] correspond juste à un point littéral.
- L'antislash (\) est le caractère d'échappement : il transforme un token spécial en caractère littéral et inversement.
- Les moteurs diffèrent : Python, JavaScript, PCRE et Golang partagent la plupart des tokens, mais les drapeaux et le look-around varient.
Questions fréquentes
- Que fait le point (.) ?
- Par défaut le point correspond à n'importe quel caractère sauf une nouvelle ligne. Pour correspondre à un point littéral, on l'échappe avec \.
- Quelle est la différence entre * et + ?
- L'astérisque * correspond au token précédent zéro ou plusieurs fois, donc 'ab*' correspond aussi à 'a'. Le plus + exige au moins un, il matche 'ab' mais pas seulement 'a'.
- Comment correspondre à un chiffre ou un caractère de mot ?
- Utilisez \d pour un chiffre (0-9) et \w pour un caractère de mot (lettres, chiffres et souligné). Leurs négations sont \D et \W.
- À quoi servent ^ et $ ?
- ^ ancre la correspondance au début de la chaîne ou de la ligne ; $ l'ancre à la fin. Ensemble, ^motif$ force toute la chaîne à correspondre.