Cheat sheet dasar regex

Ekspresi reguler (regex) adalah pola yang cocok dengan teks. Setiap simbol, yang disebut token, mengubah perilaku pola. Lembar di bawah mencantumkan token paling sering dipakai, dengan arti sederhana dan contoh kecil untuk disalin dan diuji.

Diperbarui:

TokenArtiContoh
.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

Catatan

Pertanyaan umum

Apa yang cocok dengan titik (.)?
Secara default titik cocok dengan karakter apa pun kecuali baris baru. Untuk cocok dengan titik literal, escape sebagai \.
Apa bedanya * dan + ?
Bintang * cocok dengan token sebelumnya nol atau lebih kali, jadi 'ab*' juga cocok dengan 'a'. Plus + butuh minimal satu, cocok dengan 'ab' tapi tidak hanya 'a'.
Bagaimana mencocokkan digit atau karakter kata?
Gunakan \d untuk digit apa pun (0-9) dan \w untuk karakter kata (huruf, digit, garis bawah). Negasinya adalah \D dan \W.
Untuk apa ^ dan $ ?
^ mengunci kecocokan di awal string atau baris; $ di akhir. Bersama-sama, ^pola$ memaksa seluruh string cocok.