Lesson 1/6 9 min

The pattern: matching text

A regex is a Ctrl+F that describes a shape instead of an exact text. We start with the literal pattern and the dot wildcard.

Un Ctrl+F qui décrit une forme

Tu connais déjà Ctrl+F. Tu tapes « chat », l\'éditeur surligne tous les « chat » du texte. Parfait, tant que tu cherches un mot précis.

Mais change la question. « Trouve-moi tous les codes postaux. » « Trouve-moi toutes les dates. » « Trouve-moi toutes les adresses e-mail. » Là, Ctrl+F est perdu. Tu ne peux pas lui taper « tous les codes postaux » : il cherche ce texte-là, à la lettre.

C\'est exactement le trou que la regex vient combler. Une expression régulière, c\'est un Ctrl+F qui décrit une forme au lieu d\'un texte exact. Au lieu de dire « ce mot précis », tu dis « cinq chiffres collés », ou « des lettres, un arobase, des lettres, un point ». Tu décris le motif, le moteur trouve tout ce qui lui ressemble.

On commence tout en bas de l\'échelle : le motif le plus simple qui soit, le texte littéral. Puis on ajoute le premier caractère magique, le point. Et tu écriras tes premières regex dans un labo, dès cette leçon.

Le motif littéral : du Ctrl+F déguisé

La regex la plus simple ne contient aucune magie. Le motif chat matche les caractères c, h, a, t, dans cet ordre, collés. Exactement comme Ctrl+F. Si le texte contient cette suite de lettres, ça matche.

Première surprise, et elle est importante. Le motif chat matche aussi à l\'intérieur d\'un mot plus grand. Il matche dans « chaton », parce que « chaton » contient bien c-h-a-t. Il matche dans « achat », pour la même raison. La regex ne cherche pas « le mot chat tout seul » : elle cherche cette suite de lettres, où qu\'elle se trouve.

Garde ça en tête : par défaut, un motif matche dès qu\'il trouve sa suite de caractères, même nichée dans un mot plus grand. Si tu veux exiger « le mot chat entier, pas dedans », il faudra le dire explicitement. C\'est tout l\'objet de la leçon 4, sur les ancres et les frontières. Pour l\'instant, retiens juste que « ça matche dedans », c\'est le comportement normal.

À toi de le constater toi-même dans un vrai labo.

🎯 Labo regex · matcher le mot chat
//
Bloqué ? Voir une solution

Solution : chat. Tu tapes simplement les quatre lettres, sans rien d\'autre. Le moteur les retrouve dans « chat », mais aussi à l\'intérieur de « chaton » et de « achat ». Et il ne les trouve pas dans « chien », qui ne contient pas la suite c-h-a-t. C\'est le motif littéral dans toute sa simplicité.

Le point : le joker qui matche n\'importe quel caractère

Voici ton premier caractère magique. Le point . matche un caractère, n\'importe lequel. Une lettre, un chiffre, un espace, un symbole : peu importe, le point l\'accepte. Une seule règle : un point, c\'est exactement un caractère (et il ne franchit pas un saut de ligne).

Le motif ch.t demande donc : un c, un h, n\'importe quel caractère, puis un t. Il matche « chat », mais aussi « chut », « chot » ou « ch9t ». Le point tient la place d\'un caractère sans imposer lequel.

Mais ce pouvoir a un revers, et c\'est le piège vedette de toute la regex.

Le point n\'est pas un point. Tu veux matcher le nombre « 3.14 » ? Le motif 3.14 ne fait pas ce que tu crois. Ce point au milieu est un joker : il matche n\'importe quel caractère. Donc 3.14 matche aussi « 3X14 », « 3 14 » ou « 3z14 ». Pour matcher un vrai point, le caractère point, tu dois l\'échapper avec un antislash : 3\.14. Là, et seulement là, le motif exige un point littéral.

Cette règle vaut pour toute une famille de caractères. Dans une regex, ., *, +, ?, (, ), [ et ] ont des pouvoirs spéciaux. Pour matcher l\'un de ces caractères lui-même, tu le fais précéder d\'un antislash. Tu verras chacun de leurs pouvoirs dans les prochaines leçons ; pour l\'instant, retiens la mécanique : antislash devant, et le caractère redevient lui-même.

🎯 Labo regex · matcher un vrai point
//
Bloqué ? Voir une solution

Solution : 3\.14. L\'antislash transforme le point joker en point littéral : le motif exige maintenant exactement « 3 », un point, « 14 ». Du coup « 3X14 » est rejeté (X n\'est pas un point) et « 3514 » aussi (le 5 n\'est pas un point). Si tu avais tapé 3.14 sans antislash, les trois lignes auraient matché, car le point aurait accepté le X comme le 5.

Mélanger littéral et joker

Tu as maintenant les deux briques de base : des lettres fixes, et le point qui tient une place libre. On les combine. Trouve un motif qui matche « cat », « cot » et « cut », mais pas « coat ».

Réfléchis à la forme. Les trois mots qui doivent matcher ont une lettre fixe au début, une lettre fixe à la fin, et un seul caractère qui change au milieu. « coat », lui, a deux caractères au milieu. Le point matche exactement un caractère : c\'est précisément ce qu\'il te faut.

🎯 Labo regex · une lettre au milieu
//
Bloqué ? Voir une solution

Solution : c.t. Un c, un point joker pour la lettre du milieu, un t. « cat », « cot » et « cut » collent : une seule lettre entre le c et le t. « coat » échoue, car il a deux lettres (o et a) entre le c et le t, et le point n\'en tient qu\'une. C\'est toute la puissance du point : décrire « un caractère, peu importe lequel ».

Au passage : la casse compte

Une dernière chose à savoir avant de t\'entraîner. Par défaut, une regex distingue les majuscules des minuscules. Le motif Chat (avec un C majuscule) ne matche pas « chat » (avec un c minuscule). Pour le moteur, ce sont deux caractères différents.

Il existe un réglage pour ignorer la casse, le flag i, qui rend le motif insensible majuscule/minuscule. On le détaillera en leçon 6, avec tous les autres flags. Pour l\'instant, retiens juste le principe : sans réglage particulier, C et c ne sont pas la même chose.

A Ctrl+F that describes a shape

You already know Ctrl+F. You type "cat", the editor highlights every "cat" in the text. Perfect, as long as you're looking for an exact word.

Now change the question. "Find me every postal code." "Find me every date." "Find me every e-mail address." Here, Ctrl+F is lost. You can't type "every postal code" into it: it looks for that literal text, to the letter.

That's exactly the gap a regex fills. A regular expression is a Ctrl+F that describes a shape instead of an exact text. Instead of saying "this precise word", you say "five digits stuck together", or "letters, an at-sign, letters, a dot". You describe the pattern, the engine finds everything that looks like it.

We start at the very bottom of the ladder: the simplest pattern there is, literal text. Then we add the first magic character, the dot. And you'll write your first regexes in a lab, from this very lesson.

The literal pattern: Ctrl+F in disguise

The simplest regex contains no magic at all. The pattern cat matches the characters c, a, t, in that order, stuck together. Exactly like Ctrl+F. If the text contains that run of letters, it matches.

First surprise, and it's an important one. The pattern cat also matches inside a bigger word. It matches in "cats", because "cats" does contain c-a-t. It matches in "scatter", for the same reason. The regex isn't looking for "the word cat on its own": it's looking for that run of letters, wherever it appears.

Keep this in mind: by default, a pattern matches as soon as it finds its run of characters, even nested inside a bigger word. If you want to require "the whole word cat, not inside another", you'll have to say so explicitly. That's the whole point of lesson 4, on anchors and boundaries. For now, just remember that "it matches inside" is the normal behaviour.

Go see it for yourself in a real lab.

🎯 Regex lab · match the word cat
//
Stuck? See one solution

Solution: cat. You simply type the three letters, nothing else. The engine finds them in "cat", but also inside "cats" and "scatter". And it doesn't find them in "dog", which doesn't contain the run c-a-t. That's the literal pattern in all its simplicity.

The dot: the wildcard that matches any character

Here's your first magic character. The dot . matches one character, any one. A letter, a digit, a space, a symbol: it doesn't matter, the dot accepts it. One rule only: a dot is exactly one character (and it doesn't cross a line break).

So the pattern ch.t asks for: a c, an h, any character, then a t. It matches "chat", but also "chut", "chot" or "ch9t". The dot holds the place of a character without imposing which one.

But this power has a downside, and it's the headline trap of all of regex.

Beware, the dot is not a dot. Want to match the number "3.14"? The pattern 3.14 doesn't do what you think. That dot in the middle is a wildcard: it matches any character. So 3.14 also matches "3X14", "3 14" or "3z14". To match a real dot, the dot character, you must escape it with a backslash: 3\.14. There, and only there, the pattern requires a literal dot.

This rule applies to a whole family of characters. In a regex, ., *, +, ?, (, ), [ and ] have special powers. To match one of these characters itself, you put a backslash in front of it. You'll see each of their powers in the coming lessons; for now, remember the mechanic: backslash in front, and the character becomes itself again.

🎯 Regex lab · match a real dot
//
Stuck? See one solution

Solution: 3\.14. The backslash turns the wildcard dot into a literal dot: the pattern now requires exactly "3", a dot, "14". So "3X14" is rejected (X is not a dot) and "3514" too (the 5 is not a dot). Had you typed 3.14 without the backslash, all three lines would have matched, because the dot would have accepted the X as well as the 5.

Mixing literal and wildcard

You now have the two basic bricks: fixed letters, and the dot that holds a free spot. Let's combine them. Find a pattern that matches "cat", "cot" and "cut", but not "coat".

Think about the shape. The three words that must match have a fixed letter at the start, a fixed letter at the end, and one single character changing in the middle. "coat", on the other hand, has two characters in the middle. The dot matches exactly one character: that's precisely what you need.

🎯 Regex lab · one letter in the middle
//
Stuck? See one solution

Solution: c.t. A c, a wildcard dot for the middle letter, a t. "cat", "cot" and "cut" fit: a single letter between the c and the t. "coat" fails, because it has two letters (o and a) between the c and the t, and the dot holds only one. That's the whole power of the dot: describing "one character, any one".

By the way: case matters

One last thing to know before you practise. By default, a regex distinguishes uppercase from lowercase. The pattern Cat (with a capital C) does not match "cat" (with a lowercase c). To the engine, those are two different characters.

There's a setting to ignore case, the i flag, which makes the pattern case-insensitive. We'll detail it in lesson 6, along with all the other flags. For now, just remember the principle: with no special setting, C and c are not the same thing.

🎯 Pratique

S'entraîner (clique pour ouvrir) :

💬 Ré-explique sans regarder
Ré-explique sans regarder

Explique à un collègue la différence entre le motif chat et le motif ch.t, et pourquoi 3.14 ne matche pas seulement « 3.14 ».

Une bonne explication dit : chat est un motif littéral, il exige les lettres c-h-a-t exactement, où qu'elles soient (même dans « chaton »). Dans ch.t, le point est un joker : il tient la place d'un caractère quelconque, donc « chat », « chut », « chot »… Et 3.14 piège : ce point est un joker, il matche aussi « 3X14 ». Pour un vrai point, on l'échappe : 3\.14.
🧠 Rappel libre
Rappel libre

Sans remonter : que matche le point . dans une regex, et comment fais-tu pour matcher un vrai caractère point ?

Le point . matche un caractère quelconque (sauf un saut de ligne) : lettre, chiffre, espace, symbole. C'est un joker. Pour matcher un vrai point, le caractère « . », on l'échappe avec un antislash : \.. Ainsi 3\.14 exige bien un point au milieu, et rejette « 3X14 ».
⚖️ Juge le code de l'IA
Accepter ou rejeter le code de l'IA

Tu demandes à l'IA un motif pour matcher l'adresse IP « 192.168.0.1 ». Elle répond : « Facile, utilise 192.168.0.1, ça matche ton IP. » Tu acceptes, ou tu rejettes ?

À rejeter. Le motif 192.168.0.1 matche bien ton IP… mais ses points sont des jokers : il matche aussi « 192X168X0X1 », « 192a168b0c1 », n'importe quoi à la place des points. Pour une vraie IP, il faut échapper chaque point : 192\.168\.0\.1. Règle d'or : dans une regex, un point n'est jamais un point tant qu'on ne l'a pas échappé.
Le motif chat, appliqué au mot « chaton », que fait-il ?
Que matche le point . dans une expression régulière ?
Tu veux matcher exactement le nombre « 3.14 » et rien d'autre. Quel motif choisis-tu ?
Le motif prix: 1.50 est censé matcher « prix: 1.50 ». Pourquoi matche-t-il aussi « prix: 1x50 » ?
Next step

The dot matches ANY character. Often too broad: you wanted a digit, it also accepts a letter. Lesson 2: choosing exactly WHICH ones, with classes [abc], ranges like [a-z], and the essential shorthands \d, \w and \s.

Lesson 2: Character classes →

Spotted an error in this lesson, something unclear, a question? Email me: every message helps improve this course.

Besoin d'un développeur pour votre projet ?

Réponse sous 24h · Sans engagement