Testeur Regex
Testez des expressions régulières sur une chaîne et visualisez toutes les correspondances surlignées
Motif
Chaîne de test
Qu'est-ce qu'une expression régulière ?
Une expression régulière (regex ou regexp) est une séquence de caractères qui définit un motif de recherche. Les testeurs de regex permettent d'écrire un motif, de l'exécuter sur un texte d'exemple et de voir toutes les correspondances surlignées en temps réel. Le concept remonte aux travaux du mathématicien Stephen Kleene sur les langages réguliers dans les années 1950, et Ken Thompson a intégré le premier moteur regex dans l'éditeur de texte QED en 1968.
Un moteur regex lit un motif de gauche à droite en consommant les caractères de l'entrée au fil de la recherche. Il utilise le backtracking lorsqu'une correspondance partielle échoue : le moteur recule et essaie des chemins alternatifs dans le motif. Certains moteurs (comme RE2 utilisé dans Go) évitent complètement le backtracking en convertissant les motifs en automates finis déterministes (DFA), ce qui garantit une correspondance en temps linéaire au prix de l'absence de fonctionnalités comme les références arrières.
La syntaxe regex est standardisée de manière souple. PCRE (Perl Compatible Regular Expressions) est la variante la plus répandue, supportée par PHP, le module re de Python et JavaScript avec de légères différences. POSIX définit une syntaxe plus limitée utilisée par grep et sed. Ces différences ont leur importance lors du portage de motifs entre langages : un lookahead qui fonctionne en JavaScript peut ne pas compiler du tout dans le moteur RE2 de Go.
Pourquoi utiliser un testeur de regex en ligne ?
Écrire une regex dans un fichier de code implique de sauvegarder, exécuter et inspecter le résultat à chaque ajustement du motif. Un testeur de regex dans le navigateur réduit cette boucle de retour à zéro : vous tapez, vous voyez les correspondances.
Cas d'usage du testeur de regex
Référence rapide de la syntaxe regex
Le tableau ci-dessous couvre les tokens regex les plus utilisés. Ils fonctionnent en JavaScript, Python, Go, PHP et la plupart des moteurs compatibles PCRE. Les extensions spécifiques à chaque langage (comme les motifs conditionnels de Python ou les groupes nommés de JavaScript avec la syntaxe \k) sont mentionnées dans la section des exemples de code.
| Motif | Nom | Description |
|---|---|---|
| . | Any character | Matches any single character except newline (unless s flag is set) |
| \d | Digit | Matches [0-9] |
| \w | Word character | Matches [a-zA-Z0-9_] |
| \s | Whitespace | Matches space, tab, newline, carriage return, form feed |
| \b | Word boundary | Matches the position between a word character and a non-word character |
| ^ | Start of string/line | Matches the start of the input; with m flag, matches start of each line |
| $ | End of string/line | Matches the end of the input; with m flag, matches end of each line |
| * | Zero or more | Matches the preceding token 0 or more times (greedy) |
| + | One or more | Matches the preceding token 1 or more times (greedy) |
| ? | Optional | Matches the preceding token 0 or 1 time |
| {n,m} | Quantifier range | Matches the preceding token between n and m times |
| () | Capturing group | Groups tokens and captures the matched text for back-references |
| (?:) | Non-capturing group | Groups tokens without capturing the matched text |
| (?=) | Positive lookahead | Matches a position followed by the given pattern, without consuming it |
| (?<=) | Positive lookbehind | Matches a position preceded by the given pattern, without consuming it |
| [abc] | Character class | Matches any one of the characters inside the brackets |
| [^abc] | Negated class | Matches any character not inside the brackets |
| | | Alternation | Matches the expression before or after the pipe |
Les drapeaux regex expliqués
Les drapeaux (aussi appelés modificateurs) changent la façon dont le moteur traite le motif. En JavaScript, vous les ajoutez après le slash de fermeture : /pattern/gi. En Python, vous les passez en second argument : re.findall(pattern, text, re.IGNORECASE | re.MULTILINE). Tous les drapeaux ne sont pas disponibles dans chaque langage.
| Drapeau | Nom | Comportement |
|---|---|---|
| g | Global | Find all matches, not just the first one |
| i | Case-insensitive | Letters match both uppercase and lowercase |
| m | Multiline | ^ and $ match start/end of each line, not just the whole string |
| s | Dot-all | . matches newline characters as well |
| u | Unicode | Treat the pattern and subject as a Unicode string; enables \u{FFFF} syntax |
| y | Sticky | Matches only from the lastIndex position in the target string |
Exemples de code
Exemples de regex fonctionnels en JavaScript, Python, Go et en ligne de commande. Chaque exemple illustre la construction du motif, l'extraction des correspondances et la sortie.
// Match all email addresses in a string
const text = 'Contact us at support@example.com or sales@example.com'
const emailRegex = /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g
const matches = text.matchAll(emailRegex)
for (const match of matches) {
console.log(match[0], 'at index', match.index)
}
// → "support@example.com" at index 14
// → "sales@example.com" at index 37
// Named capture groups (ES2018+)
const dateRegex = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/
const result = '2026-03-30'.match(dateRegex)
console.log(result.groups)
// → { year: "2026", month: "03", day: "30" }
// Replace with a callback
'hello world'.replace(/\b\w/g, c => c.toUpperCase())
// → "Hello World"import re
# Find all IPv4 addresses
text = 'Server 192.168.1.1 responded, fallback to 10.0.0.255'
pattern = r'\b(?:\d{1,3}\.){3}\d{1,3}\b'
matches = re.findall(pattern, text)
print(matches) # → ['192.168.1.1', '10.0.0.255']
# Named groups and match objects
date_pattern = r'(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})'
m = re.search(date_pattern, 'Released on 2026-03-30')
if m:
print(m.group('year')) # → '2026'
print(m.group('month')) # → '03'
# Compile for repeated use (faster in loops)
compiled = re.compile(r'\b[A-Z][a-z]+\b')
words = compiled.findall('Hello World Foo bar')
print(words) # → ['Hello', 'World', 'Foo']package main
import (
"fmt"
"regexp"
)
func main() {
// Find all matches
re := regexp.MustCompile(`\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}\b`)
text := "Contact support@example.com or sales@example.com"
matches := re.FindAllString(text, -1)
fmt.Println(matches)
// → [support@example.com sales@example.com]
// Named capture groups
dateRe := regexp.MustCompile(`(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})`)
match := dateRe.FindStringSubmatch("2026-03-30")
for i, name := range dateRe.SubexpNames() {
if name != "" {
fmt.Printf("%s: %s\n", name, match[i])
}
}
// → year: 2026
// → month: 03
// → day: 30
// Replace with a function
result := re.ReplaceAllStringFunc(text, func(s string) string {
return "[REDACTED]"
})
fmt.Println(result)
// → Contact [REDACTED] or [REDACTED]
}# Find lines matching an IP address pattern
grep -E '\b([0-9]{1,3}\.){3}[0-9]{1,3}\b' access.log
# Extract email addresses from a file
grep -oE '[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}' contacts.txt
# Replace dates from YYYY-MM-DD to DD/MM/YYYY using sed
echo "2026-03-30" | sed -E 's/([0-9]{4})-([0-9]{2})-([0-9]{2})/\3\/\2\/\1/'
# → 30/03/2026
# Count matches per file in a directory
grep -rcE 'TODO|FIXME|HACK' src/
# → src/main.js:3
# → src/utils.js:1