Testador de Regex
Teste expressões regulares em um texto e veja todas as correspondências destacadas
Padrão
Texto de teste
O que é uma expressão regular?
Uma expressão regular (regex ou regexp) é uma sequência de caracteres que define um padrão de busca. Testadores de regex permitem escrever um padrão, executá-lo em um texto de amostra e ver todas as correspondências destacadas em tempo real. O conceito remonta ao trabalho do matemático Stephen Kleene sobre linguagens regulares nos anos 1950, e Ken Thompson incorporou o primeiro motor de regex ao editor de texto QED em 1968.
Um motor de regex lê um padrão da esquerda para a direita, consumindo caracteres da entrada enquanto tenta encontrar correspondências. Ele usa backtracking quando uma correspondência parcial falha: o motor recua e tenta caminhos alternativos pelo padrão. Alguns motores (como o RE2 usado no Go) evitam o backtracking inteiramente convertendo padrões em autômatos finitos determinísticos (DFA), o que garante correspondência em tempo linear ao custo de não suportar recursos como referências retroativas.
A sintaxe de regex é padronizada de forma aproximada. O PCRE (Perl Compatible Regular Expressions) é o dialeto mais comum, suportado por PHP, pelo módulo re do Python e pelo JavaScript com pequenas diferenças. O POSIX define uma sintaxe mais limitada usada pelo grep e pelo sed. As diferenças importam ao portar padrões entre linguagens: um lookahead que funciona em JavaScript pode não compilar no motor RE2 do Go.
Por que usar um testador de regex online?
Escrever regex em um arquivo de código exige salvar, executar e inspecionar a saída a cada ajuste no padrão. Um testador de regex no navegador elimina completamente esse ciclo: você digita e vê as correspondências.
Casos de uso do testador de regex
Referência rápida de sintaxe regex
A tabela abaixo cobre os tokens de regex mais usados. Eles funcionam em JavaScript, Python, Go, PHP e na maioria dos motores compatíveis com PCRE. Extensões específicas de cada linguagem (como os padrões condicionais do Python ou os grupos nomeados do JavaScript com sintaxe \k) são indicadas na seção de exemplos de código.
| Padrão | Nome | Descrição |
|---|---|---|
| . | 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 |
Flags de regex explicadas
Flags (também chamadas de modificadores) alteram como o motor processa o padrão. Em JavaScript você as adiciona após a barra de fechamento: /padrão/gi. Em Python você as passa como segundo argumento: re.findall(padrão, texto, re.IGNORECASE | re.MULTILINE). Nem todas as flags estão disponíveis em todas as linguagens.
| Flag | Nome | Comportamento |
|---|---|---|
| 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 |
Exemplos de código
Exemplos funcionais de regex em JavaScript, Python, Go e na linha de comando. Cada exemplo mostra a construção do padrão, a extração de correspondências e a saída.
// 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