Les expressions regulieres (regex) sont un outil puissant pour tout developpeur. Que vous validiez des saisies utilisateur, analysiez des logs ou effectuiez des operations de recherche-remplacement, les regex offrent une precision inegalee. Cette aide-memoire regex complete couvre tous les concepts majeurs : ancres, classes de caracteres, quantificateurs, groupes, assertions et flags.
Testez chaque motif en direct dans notre Regex Tester ->
Syntaxe de base : Ancres et classes de caracteres
Les ancres et classes de caracteres forment la base de tout motif regex. Les ancres specifient ou dans la chaine une correspondance doit se produire. Les classes definissent quels caracteres correspondre.
Ancres
Les ancres ne correspondent pas a des caracteres, mais a des positions dans la chaine.
| Pattern | Description | Example |
|---|---|---|
^ | Start of string (or line with m flag) | ^Hello matches "Hello World" |
$ | End of string (or line with m flag) | world$ matches "Hello world" |
\b | Word boundary | \bcat\b matches "cat" but not "catch" |
\B | Non-word boundary | \Bcat\B matches "concatenate" |
\A | Absolute start of string (Python, Ruby) | \AHello |
\Z | Absolute end of string (Python, Ruby) | bye\Z |
Classes de caracteres
Les classes de caracteres permettent de correspondre a un ensemble de caracteres a une position donnee.
| Pattern | Description | Equivalent |
|---|---|---|
[abc] | Match a, b, or c | -- |
[^abc] | Match anything except a, b, c | -- |
[a-z] | Match any lowercase letter | -- |
[A-Z] | Match any uppercase letter | -- |
[0-9] | Match any digit | \d |
. | Match any character (except newline by default) | -- |
\d | Digit | [0-9] |
\D | Non-digit | [^0-9] |
\w | Word character | [a-zA-Z0-9_] |
\W | Non-word character | [^a-zA-Z0-9_] |
\s | Whitespace (space, tab, newline) | [ \t\n\r\f\v] |
\S | Non-whitespace | [^ \t\n\r\f\v] |
Caracteres speciaux (metacaracteres)
Ces caracteres ont une signification speciale en regex. Pour les correspondre litteralement, echappez-les avec un antislash.
Special characters that need escaping:
. ^ $ * + ? { } [ ] \ | ( )
To match a literal dot: \.
To match a literal star: \*
To match a literal pipe: \|
To match a backslash: \\Quantificateurs : combien de fois correspondre
Les quantificateurs controlent le nombre de repetitions. Par defaut, ils sont gourmands. Ajouter ? les rend paresseux.
| Greedy | Lazy | Description |
|---|---|---|
* | *? | 0 or more times |
+ | +? | 1 or more times |
? | ?? | 0 or 1 time (optional) |
{n} | {n}? | Exactly n times |
{n,} | {n,}? | n or more times |
{n,m} | {n,m}? | Between n and m times |
Gourmand vs. Paresseux
Le motif gourmand <.*> correspond a la chaine entiere, tandis que <.*?> ne correspond qu'a la premiere balise.
// Input string:
const str = '<b>bold</b> and <i>italic</i>';
// Greedy: matches from first < to LAST >
str.match(/<.*>/);
// Result: '<b>bold</b> and <i>italic</i>'
// Lazy: matches from first < to FIRST >
str.match(/<.*?>/);
// Result: '<b>'Groupes et capture
Les groupes permettent de traiter plusieurs caracteres comme une unite et d'extraire des portions correspondantes.
Groupes de capture
Encadrez une sous-expression avec (...) pour capturer sa correspondance.
// Capturing group example
const dateRegex = /^(\d{4})-(\d{2})-(\d{2})$/;
const match = '2026-02-10'.match(dateRegex);
// match[0] = '2026-02-10' (full match)
// match[1] = '2026' (year)
// match[2] = '02' (month)
// match[3] = '10' (day)
// Backreference: match repeated words
const repeated = /\b(\w+)\s+\1\b/;
repeated.test('the the'); // true
repeated.test('the cat'); // falseGroupes nommes
Les groupes nommes ameliorent la lisibilite avec la syntaxe (?<nom>...).
// Named groups in JavaScript
const dateRegex = /^(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})$/;
const match = '2026-02-10'.match(dateRegex);
// match.groups.year = '2026'
// match.groups.month = '02'
// match.groups.day = '10'# Named groups in Python
import re
pattern = r'^(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})$'
m = re.match(pattern, '2026-02-10')
# m.group('year') = '2026'
# m.group('month') = '02'
# m.group('day') = '10'Groupes non capturants
Utilisez (?:...) quand le groupement est necessaire sans capture.
// Non-capturing group
const regex = /(?:https?|ftp):\/\/[^\s]+/;
// Groups the protocol options without capturing them
// Only the full URL is in match[0]Alternance (OU)
Utilisez le pipe | dans un groupe pour correspondre a une alternative.
// Alternation examples
/cat|dog/ // Match "cat" or "dog"
/(red|blue) car/ // Match "red car" or "blue car"
/^(GET|POST|PUT|DELETE)\s/ // Match HTTP methodsLookahead et Lookbehind (assertions de largeur zero)
Les assertions verifient qu'un motif existe (ou non) avant ou apres la position actuelle, sans consommer de caracteres.
| Syntax | Type | Description |
|---|---|---|
(?=...) | Positive lookahead | What follows must match |
(?!...) | Negative lookahead | What follows must NOT match |
(?<=...) | Positive lookbehind | What precedes must match |
(?<!...) | Negative lookbehind | What precedes must NOT match |
Lookahead positif (?=...)
Correspond a une position suivie par le motif specifie.
// Match a number followed by "px"
/\d+(?=px)/
// "20px 30em 40px" → matches "20" and "40" (not "30")
// Password: must contain at least one digit
/^(?=.*\d).{8,}$/Lookahead negatif (?!...)
Correspond a une position non suivie par le motif specifie.
// Match "cat" NOT followed by "fish"
/cat(?!fish)/
// "catfish catdog" → matches "cat" in "catdog" only
// Match numbers NOT followed by a unit
/\d+(?!\s*(px|em|rem|%))/Lookbehind positif (?<=...)
Correspond a une position precedee par le motif specifie.
// Match a number preceded by "$"
/(?<=\$)\d+(\.\d{2})?/
// "$49.99 and €29.99" → matches "49.99" only
// Extract value after "price:"
/(?<=price:\s*)\d+/Lookbehind negatif (?<!...)
Correspond a une position non precedee par le motif specifie.
// Match "cat" NOT preceded by "wild"
/(?<!wild)cat/
// "wildcat housecat" → matches "cat" in "housecat" only
// Match digits not preceded by a minus sign
/(?<!-)\b\d+\b/Note : Les lookbehinds ne sont pas supportes par tous les moteurs regex.
Flags Regex (modificateurs)
Les flags modifient l'interpretation du motif par le moteur regex.
| Flag | Name | Description | Example |
|---|---|---|---|
g | Global | Find all matches, not just the first | /cat/g finds all "cat" occurrences |
i | Case-insensitive | Match upper and lowercase interchangeably | /hello/i matches "Hello", "HELLO" |
m | Multiline | ^ and $ match line starts/ends | /^start/m matches at each line start |
s | Dotall (Single-line) | . matches newline characters too | /a.b/s matches "a\nb" |
u | Unicode | Enable full Unicode matching | /\u{1F600}/u matches emoji |
y | Sticky | Match only at lastIndex position | Used for tokenizing / lexing |
// Combining flags
const regex = /^hello world$/gim;
// In Python, flags are constants:
import re
pattern = re.compile(r'^hello world$', re.IGNORECASE | re.MULTILINE)
// In Go, use inline flags:
// (?i) for case-insensitive, (?m) for multiline, (?s) for dotall
regexp.MustCompile("(?im)^hello world$")Motifs courants - Reference rapide
Voici les motifs regex les plus frequemment utilises.
| Use Case | Pattern |
|---|---|
^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$ | |
| URL (HTTP/S) | ^https?:\/\/[^\s]+$ |
| IPv4 Address | ^((25[0-5]|(2[0-4]|1\d|[1-9]|)\d)\.?\b){4}$ |
| Date (YYYY-MM-DD) | ^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$ |
| Time (HH:MM:SS) | ^([01]\d|2[0-3]):[0-5]\d:[0-5]\d$ |
| Hex Color | ^#([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$ |
| Strong Password | ^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&]).{8,}$ |
| Phone (E.164) | ^\+[1-9]\d{1,14}$ |
| UUID | ^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$ |
| Semantic Version | ^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(-[\w.]+)?(\+[\w.]+)?$ |
| HTML Tag | <([a-zA-Z][a-zA-Z0-9]*)\b[^>]*>(.*?)<\/\1> |
| Trim Whitespace | ^\s+|\s+$ |
Testez tous ces motifs avec notre Regex Tester ->
Regex dans differents langages de programmation
Bien que la syntaxe soit largement universelle, chaque langage a sa propre API.
JavaScript
// Creating regex in JavaScript
const regex1 = /^\d+$/; // Literal syntax
const regex2 = new RegExp('^\\d+$'); // Constructor (needs double-escape)
// Testing
regex1.test('12345'); // true
// Matching
'hello world'.match(/\w+/g); // ['hello', 'world']
// Replacing
'2026-02-10'.replace(
/^(\d{4})-(\d{2})-(\d{2})$/,
'$2/$3/$1'
); // '02/10/2026'
// matchAll (ES2020) - get all matches with groups
const text = 'Price: $10, Tax: $2';
for (const m of text.matchAll(/\$(\d+)/g)) {
console.log(m[0], m[1]);
// '$10' '10', then '$2' '2'
}
// Named groups (ES2018+)
const { groups } = '2026-02-10'.match(
/(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/
);
console.log(groups.year); // '2026'Python
import re
# Compile for reuse (recommended)
pattern = re.compile(r'^\d+$')
# Test if the entire string matches
pattern.match('12345') # Match object (truthy)
pattern.match('abc') # None (falsy)
# Search anywhere in the string
re.search(r'\d+', 'abc 123 def') # Finds '123'
# Find all matches
re.findall(r'\w+', 'hello world') # ['hello', 'world']
# Replace
re.sub(
r'^(\d{4})-(\d{2})-(\d{2})$',
r'\2/\3/\1',
'2026-02-10'
) # '02/10/2026'
# Named groups
m = re.match(
r'(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})',
'2026-02-10'
)
m.group('year') # '2026'
m.group('month') # '02'
# Flags
re.findall(r'^start', text, re.MULTILINE | re.IGNORECASE)
# Split by pattern
re.split(r'[,;\s]+', 'a, b; c d') # ['a', 'b', 'c', 'd']Go (Golang)
package main
import (
"fmt"
"regexp"
)
func main() {
// Compile (panics on invalid pattern)
re := regexp.MustCompile(`^\d+$`)
// Test
fmt.Println(re.MatchString("12345")) // true
fmt.Println(re.MatchString("abc")) // false
// Find first match
re2 := regexp.MustCompile(`\d+`)
fmt.Println(re2.FindString("abc 123 def")) // "123"
// Find all matches
fmt.Println(re2.FindAllString("10 cats and 20 dogs", -1))
// ["10", "20"]
// Replace
re3 := regexp.MustCompile(`(\d{4})-(\d{2})-(\d{2})`)
result := re3.ReplaceAllString("2026-02-10", "$2/$3/$1")
fmt.Println(result) // "02/10/2026"
// Named groups
re4 := regexp.MustCompile(`(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})`)
match := re4.FindStringSubmatch("2026-02-10")
for i, name := range re4.SubexpNames() {
if name != "" {
fmt.Printf("%s: %s\n", name, match[i])
}
}
// year: 2026, month: 02, day: 10
// Inline flags: (?i) case-insensitive, (?m) multiline, (?s) dotall
re5 := regexp.MustCompile(`(?i)hello`)
fmt.Println(re5.MatchString("HELLO")) // true
}Go utilise RE2, qui ne supporte pas les lookaheads, lookbehinds ou references arriere.
Conseils de performance et bonnes pratiques
Soyez specifique : Utilisez [a-zA-Z] plutot que . quand possible.
Evitez le backtracking catastrophique : Les quantificateurs imbriques comme (a+)+ peuvent causer une complexite exponentielle.
// BAD: Catastrophic backtracking risk
const bad = /^(a+)+$/;
bad.test('aaaaaaaaaaaaaaaaaaaaa!'); // Extremely slow!
// GOOD: Flatten nested quantifiers
const good = /^a+$/;
good.test('aaaaaaaaaaaaaaaaaaaaa!'); // Instant: falseUtilisez les groupes non capturants : (?:...) est plus efficace quand la capture n'est pas necessaire.
Compilez une fois : En Python et Go, compilez votre regex une fois et reutilisez l'objet compile.
# Python: compile once, reuse many times
import re
email_re = re.compile(r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$')
# Fast: uses pre-compiled pattern
for addr in addresses:
if email_re.match(addr):
print(f"Valid: {addr}")Testez incrementalement : Construisez les motifs complexes etape par etape.
Testez chaque motif en direct dans notre Regex Tester ->
Questions frequentes
Qu'est-ce qu'une aide-memoire regex et pourquoi en ai-je besoin ?
Une aide-memoire regex est un guide de reference rapide listant la syntaxe, les metacaracteres, les quantificateurs, les flags et les motifs courants. Meme les developpeurs experimentes ne peuvent pas tout memoriser.
Quelle est la difference entre .* et .*? en regex ?
.* est un quantificateur gourmand (correspondance la plus longue), tandis que .*? est paresseux (correspondance la plus courte). Utilisez le mode paresseux pour s'arreter au premier delimiteur.
Tous les langages supportent-ils la meme syntaxe regex ?
La plupart supportent PCRE ou une variante proche. Mais les fonctionnalites avancees different : JavaScript a ajoute les lookbehinds en ES2018, Go (RE2) ne supporte pas les lookbehinds.
Comment tester et deboguer les motifs regex ?
Utilisez un testeur regex interactif comme notre outil Regex Tester qui montre les correspondances en temps reel. Construisez votre motif etape par etape.
Qu'est-ce que le backtracking catastrophique ?
Il se produit quand le moteur prend un temps exponentiel pour determiner qu'une chaine ne correspond pas. Evitez les quantificateurs imbriques et soyez specifique avec les classes de caracteres.