Cheatsheet de expressões regulares

Uma expressão regular (regex) é um padrão que corresponde a texto. Cada símbolo, chamado token, muda o comportamento do padrão. A folha abaixo lista os tokens mais usados, com significado simples e um pequeno exemplo para copiar e testar.

Atualizado:

TokenSignificadoExemplo
.Matches any single character except newline.a.c matches abc, a c
*Matches the preceding token zero or more times.ab* matches a, abb
+Matches the preceding token one or more times.ab+ matches ab, abb
?Makes the preceding token optional (zero or one).colou?r matches color, colour
[]Character set: matches any one character inside.[aeiou] matches any vowel
[^]Negated set: matches any character NOT inside.[^0-9] matches any non-digit
\dMatches any digit (0-9).\d+ matches 42, 007
\wMatches any word character (a-z, A-Z, 0-9, _).\w+ matches hello_1
\sMatches any whitespace (space, tab, newline).a\sb matches a b
^Anchors the match to the start of a line/string.^Hello matches start of string
$Anchors the match to the end of a line/string.world$ matches end of string
|Alternation: matches the pattern on either side.cat|dog matches cat or dog
()Groups a sub-pattern (and captures it).(ab)+ matches ab, abab
{n,m}Quantifier: match the preceding token n to m times.a{2,4} matches aa, aaaa
(?i)Inline flag: makes the pattern case-insensitive.(?i)hello matches HELLO

Notas

Perguntas frequentes

O que o ponto (.) corresponde?
Por padrão o ponto corresponde a qualquer caractere exceto nova linha. Para corresponder a um ponto literal você deve escapá-lo como \.
Qual a diferença entre * e +?
O asterisco * corresponde ao token anterior zero ou mais vezes, então 'ab*' também casa 'a'. O mais + exige ao menos um, casando 'ab' mas não apenas 'a'.
Como faço para corresponder a um dígito ou caractere de palavra?
Use \d para qualquer dígito (0-9) e \w para qualquer caractere de palavra (letras, dígitos e sublinhado). Suas negações são \D e \W.
Para que servem ^ e $?
^ ancora a correspondência ao início da string ou linha; $ a ancora ao final. Juntos, ^padrão$ força a string inteira a corresponder.