Conventions and good practiceConventions et bonnes pratiques
The gmu flags
A regular expression runs under settings called flags, at the top right in
regex101. The module uses gmu everywhere, in the built-in tester and in the
screenshots alike:
- g (global): find every match, not only the first one;
- m (multiline): treat each line separately for the start-of-line and end-of-line anchors anchorancre regular expressionsexpressions rationnelles A regular-expression construct that matches a position in the text rather than a character, so it makes a match succeed or fail without consuming anything.Construction d'expression rationnelle qui correspond à une position dans le texte plutôt qu'à un caractère : elle fait réussir ou échouer une correspondance sans rien consommer. ;
- u (unicode): turn on full Unicode support, which is what accented letters need.
For now, take it that gmu is assumed everywhere unless a page says
otherwise.
Two other flags come up often elsewhere, and are off here: i, which makes the
search case-insensitive, and s, which lets the dot match a line break line breaksaut de ligne text encodingencodage du texte The character that ends a line in a file, stored in it like any other and invisible on screen. It is what divides a file into lines, so a file's line count is fixed : two of them make three lines, whatever width the window is. Windows writes it as two characters, a carriage return followed by a line feed (CR LF), where macOS and Linux use one (LF).Caractère qui termine une ligne dans un fichier, enregistré comme n'importe quel autre et invisible à l'écran. C'est lui qui découpe le fichier en lignes, si bien que leur nombre est fixe : deux sauts de ligne font trois lignes, quelle que soit la largeur de la fenêtre. Windows l'écrit au moyen de deux caractères, un retour chariot suivi d'un saut de ligne (CR LF), là où macOS et Linux n'en emploient qu'un (LF). too.
Meeting them in a tool is nothing unusual; the exercises in this module simply
assume they are off.
The /…/ notation
Throughout the module, expressions appear between slashes: /regex/. This is a
widespread convention in programming languages (delimiter notation), and it has
a concrete advantage: it makes visible any space at the start or the end of an
expression. / regex / has a space before and a space after the word, and both
are part of the pattern. The slashes are not: do not type them into the
exercise fields, which already show one on either side.
Good practice, from the start
Working with regular expressions is like writing code, or a translation: it is not enough that it works, it has to be understandable and reusable.
- Look for the balance between brevity and readability.
- Structure your thinking: start simple, add complexity where you need it.
- Test on varied cases, including the ones that might cause trouble: what works once does not work everywhere.
- There is rarely one “right” expression: choose according to how precise or how flexible you need to be.
- Some expressions match more text than you meant them to; the chapters that follow show how to tighten a pattern to avoid that trap.
Les drapeaux gmu
Une expression rationnelle s’exécute selon des paramètres appelés drapeaux
(flags), en haut à droite dans regex101. Le module utilise gmu partout,
dans le testeur intégré comme dans les captures d’écran :
- g (global) : trouver toutes les correspondances, pas seulement la première ;
- m (multiline) : traiter chaque ligne indépendamment pour les ancres anchorancre regular expressionsexpressions rationnelles A regular-expression construct that matches a position in the text rather than a character, so it makes a match succeed or fail without consuming anything.Construction d'expression rationnelle qui correspond à une position dans le texte plutôt qu'à un caractère : elle fait réussir ou échouer une correspondance sans rien consommer. de début et de fin de ligne ;
- u (unicode) : activer le support Unicode complet, indispensable pour couvrir les lettres accentuées du français.
Pour l’instant, retenez que le réglage gmu est supposé partout, sauf
indication contraire.
Deux autres drapeaux reviennent souvent ailleurs, et sont désactivés ici :
i, qui rend la recherche insensible à la casse, et s, qui autorise le
point à correspondre aussi à un saut de ligne line breaksaut de ligne text encodingencodage du texte The character that ends a line in a file, stored in it like any other and invisible on screen. It is what divides a file into lines, so a file's line count is fixed : two of them make three lines, whatever width the window is. Windows writes it as two characters, a carriage return followed by a line feed (CR LF), where macOS and Linux use one (LF).Caractère qui termine une ligne dans un fichier, enregistré comme n'importe quel autre et invisible à l'écran. C'est lui qui découpe le fichier en lignes, si bien que leur nombre est fixe : deux sauts de ligne font trois lignes, quelle que soit la largeur de la fenêtre. Windows l'écrit au moyen de deux caractères, un retour chariot suivi d'un saut de ligne (CR LF), là où macOS et Linux n'en emploient qu'un (LF). . Les rencontrer dans un outil
n’a rien d’étonnant ; simplement, les exercices du module supposent leur
absence.
La notation /…/
Dans tout le module, les expressions s’affichent entre barres obliques :
/regex/. C’est une convention répandue dans les langages de programmation
(delimiter notation), et elle a un avantage concret : elle rend visibles les
espaces au début ou à la fin d’une expression. / regex / contient une espace
avant et une espace après le mot, et ces espaces font partie du motif. Les
barres obliques, elles, n’en font pas partie : ne les tapez pas dans les champs
d’exercice, qui les affichent déjà de part et d’autre.
Bonnes pratiques, dès le départ
Travailler avec des expressions rationnelles ressemble à écrire du code ou une traduction : il ne suffit pas que cela fonctionne, il faut que ce soit compréhensible et réutilisable.
- Cherchez l’équilibre entre concision et lisibilité.
- Structurez votre réflexion : commencez simple, complexifiez au besoin.
- Testez sur des cas variés, y compris ceux qui pourraient poser problème : ce qui fonctionne une fois ne fonctionne pas partout.
- Il n’existe que rarement une seule « bonne » expression : choisissez selon le niveau de précision ou de souplesse dont vous avez besoin.
- Certaines expressions capturent plus de texte que prévu ; les chapitres suivants montrent comment resserrer un motif pour éviter ce piège.
Sources
- MDN Web Docs (n.d.). Regular expressions. MDN JavaScript Guide, Mozilla. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_expressions
Sources
- MDN Web Docs (n.d.). Regular expressions. MDN JavaScript Guide, Mozilla. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_expressions