Referensi cepat regex. Character classes, anchors, quantifiers, groups, lookaround, flags, dan common patterns. Perfect buat developer yang sering parsing dan validasi teks.
Dua cara bikin pattern regex di JavaScript.
// Literal notation (preferred untuk pattern statis)
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
// Constructor (untuk pattern dinamis)
const searchTerm = "hello";
const dynamicPattern = new RegExp(searchTerm, "gi");const text = "Halo, email aku adalah test@example.com";
// test() - return boolean
emailPattern.test(text); // true
// match() - return array match atau null
text.match(/\b\w+@\w+\.\w+\b/g);
// ["test@example.com"]
// matchAll() - iterator untuk semua matches dengan groups
const matches = [...text.matchAll(/(\w+)@(\w+)\.(\w+)/g)];
// matches[0][1] = "test", matches[0][2] = "example", matches[0][3] = "com"
// search() - return index pertama match
text.search(/email/); // 6
// replace() - ganti match
text.replace(/test@/, "admin@");
// "Halo, email aku adalah admin@example.com"
// split() - pisah string berdasarkan pattern
"a,b;c.d".split(/[,;.]/); // ["a", "b", "c", "d"]Tabel class yang paling sering dipake.
// \d - digit (0-9)
/\d+/.test("abc123"); // true
// \D - non-digit
/\D/.test("123"); // false
// \w - word character (a-z, A-Z, 0-9, _)
/\w+/.test("hello_123"); // true
// \W - non-word character
/\W/.test("hello!"); // true (match "!")
// \s - whitespace (space, tab, newline)
/\s/.test("hello world"); // true
// \S - non-whitespace
/\S/.test(" "); // false
// . - any character (kecuali newline)
/a.b/.test("axb"); // true
// Escape special chars: . * + ? ^ $ { } [ ] \ | ( )
/\$\d+\.\d+/.test("$19.99"); // true// [abc] - salah satu a, b, atau c
/[aeiou]/.test("hello"); // true
// [a-z] - range huruf kecil
/[a-z]/.test("ABC"); // false
// [A-Za-z0-9] - alphanumeric
/[A-Za-z0-9]+/.test("abc123"); // true
// [^abc] - negation, BUKAN a, b, atau c
/[^aeiou]/.test("a"); // false
// [0-9a-fA-F] - hexadecimal
/^[0-9a-fA-F]+$/.test("deadBEEF"); // true// ^ - awal string
/^Hello/.test("Hello World"); // true
/^World/.test("Hello World"); // false
// $ - akhir string
/World$/.test("Hello World"); // true
// \b - word boundary
/\bcat\b/.test("the cat sat"); // true
/\bcat\b/.test("category"); // false
/\bcat/.test("catch"); // true (cat di awal kata)
// \B - non-word boundary
/\Bcat/.test("concatenate"); // true (cat di tengah kata)
// ^ dan $ bersamaan = full string match
/^\d{4}$/.test("2024"); // true
/^\d{4}$/.test("20241"); // false// * - 0 atau lebih
/ab*c/.test("ac"); // true (b 0 kali)
/ab*c/.test("abbbc"); // true
// + - 1 atau lebih
/ab+c/.test("ac"); // false
/ab+c/.test("abc"); // true
// ? - 0 atau 1 (opsional)
/colou?r/.test("color"); // true
/colou?r/.test("colour"); // true
// {n} - tepat n kali
/\d{4}/.test("1234"); // true
/\d{4}/.test("123"); // false
// {n,} - minimal n kali
/\d{2,}/.test("12345"); // true
// {n,m} - antara n dan m kali
/\d{2,4}/.test("123"); // true
/\d{2,4}/.test("1"); // false
/\d{2,4}/.test("12345"); // false (lebih dari 4)const html = '<div class="a">Hello</div><div class="b">World</div>';
// Greedy (default) - match sebanyak mungkin
html.match(/<div.*>/);
// '<div class="a">Hello</div><div class="b">World</div>'
// Lazy (?) - match sesedikit mungkin
html.match(/<div.*?>/);
// '<div class="a">'
// Contoh lain
"aaa".match(/a+/); // ["aaa"] greedy
"aaa".match(/a+?/); // ["a"] lazy// (pattern) - capturing group
const date = "2024-06-21";
const match = date.match(/(\d{4})-(\d{2})-(\d{2})/);
// match[0] = "2024-06-21"
// match[1] = "2024" (year)
// match[2] = "06" (month)
// match[3] = "21" (day)
// Named groups (?<name>pattern)
const namedMatch = date.match(/(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/);
namedMatch.groups.year; // "2024"
namedMatch.groups.month; // "06"
namedMatch.groups.day; // "21"// (?:pattern) - group tanpa capture
"abc123".match(/(?:abc)(\d+)/);
// match[1] = "123" (hanya yang di-capture)
// Berguna untuk alternation tanpa capture
const yes = "yes yesn't";
yes.match(/(?:yes|no)n?/g); // ["yes", "yesn't"] - wait, n't is separate// \1, \2, dst - referensi ke group sebelumnya
// Match kata berulang
/\b(\w+)\s+\1\b/.test("hello hello"); // true
/\b(\w+)\s+\1\b/.test("hello world"); // false
// Match tanda kutip yang konsisten
/(['"])(.*?)\1/.test('"hello"'); // true
/(['"])(.*?)\1/.test("'hello'"); // true
/(['"])(.*?)\1/.test('"hello\''); // false (beda quote)// (?=pattern) - positive lookahead (setelah posisi ini, harus match)
/\d+(?=px)/.test("100px"); // true
/\d+(?=px)/.test("100em"); // false
// (?!pattern) - negative lookahead (setelah ini, TIDAK boleh match)
/\d+(?!px)/.test("100em"); // true
/\d+(?!px)/.test("100px"); // false
// (?<=pattern) - positive lookbehind (sebelum posisi ini, harus match)
/(?<=\$)\d+/.exec("$100"); // ["100"]
/(?<=\$)\d+/.exec("100"); // null
// (?<!pattern) - negative lookbehind (sebelum ini, TIDAK boleh match)
/(?<!\$)\b\d+\b/.exec("$100"); // null (ada $ sebelum angka)
/(?<!\$)\b\d+\b/.exec("100"); // ["100"]// Password: minimal 8 char, ada huruf besar, huruf kecil, dan angka
const passwordPattern = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$/;
passwordPattern.test("Password1"); // true
passwordPattern.test("password"); // false
// Angka dengan thousand separator (kecuali 4 digit di awal)
/\B(?=(\d{3})+(?!\d))/g;
"1234567".replace(/\B(?=(\d{3})+(?!\d))/g, ".");
// "1.234.567"// g - global (match semua, bukan cuma pertama)
"aaa".match(/a/g); // ["a", "a", "a"]
"aaa".match(/a/); // ["a"]
// i - case insensitive
"Hello".match(/hello/i); // ["Hello"]
// m - multiline (^ dan $ match per line)
"a\nb".match(/^b/m); // ["b"]
"a\nb".match(/^b/); // null
// s - dotall (. match newline juga)
"a\nb".match(/a.b/s); // ["a\nb"]
"a\nb".match(/a.b/); // null (tanpa s, . ngga match \n)
// y - sticky (match mulai dari lastIndex)
const sticky = /abc/y;
sticky.lastIndex = 0;
sticky.test("abcabc"); // true
sticky.lastIndex = 3;
sticky.test("abcabc"); // true
// u - unicode
/^\u{1F600}$/.test("😀"); // true (unicode mode)// | = OR
/cat|dog|bird/.test("I have a dog"); // true
// Grouping dengan alternation
/(cat|dog)s?/.test("cats"); // true
// Di dalam character class, | artinya literal pipe
/[|]/.test("a|b"); // true// Sederhana
/^[^\s@]+@[^\s@]+\.[^\s@]+$/
// Lebih ketat (RFC 5322近似)
/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/// HTTP/HTTPS URL
/^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)$/
// Extract URLs dari teks
const urlRegex = /https?:\/\/[^\s]+/g;// Format Indonesia: +62 atau 08
/^(\+62|62|0)8[1-9][0-9]{6,11}$/
// Match nomor di teks
/(\+62|62|0)8[1-9]\d{6,11}/g// IPv4
/^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$/
// IPv6 (simplified)
/^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$/// YYYY-MM-DD
/^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$/
// DD/MM/YYYY
/^(0[1-9]|[12]\d|3[01])\/(0[1-9]|1[0-2])\/\d{4}$//^[a-z0-9]+(?:-[a-z0-9]+)*$/
// "hello-world-123" match
// "Hello World" tidak match/^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/
// "#fff" match
// "#1a2b3c" match
// "#ggg" tidak match// Replace dengan function
"hello world".replace(/(\w+)/g, (match, word) => {
return word.charAt(0).toUpperCase() + word.slice(1);
});
// "Hello World"
// Swap nama
"Doe, John".replace(/(\w+),\s*(\w+)/, "$2 $1");
// "John Doe"// Groups ikut masuk ke hasil split
"a,b,c".split(/(,)/);
// ["a", ",", "b", ",", "c"]import re
# Search
re.search(r'\d+', 'abc123') # <Match object>
# Find all
re.findall(r'\d+', 'a1b2c3') # ['1', '2', '3']
# Substitute
re.sub(r'\d+', 'N', 'a1b2c3') # 'aNbNcN'
# Split
re.split(r'[,;]', 'a,b;c') # ['a', 'b', 'c']
# Named groups
m = re.search(r'(?P<year>\d{4})-(?P<month>\d{2})', '2024-06')
m.group('year') # '2024'
m.group('month') # '06'import "regexp"
re := regexp.MustCompile(`\d+`)
// Match
re.MatchString("abc123") // true
// Find
re.FindString("abc123def") // "123"
// Find all
re.FindAllString("a1b2c3", -1) // ["1", "2", "3"]
// Replace
re.ReplaceAllString("a1b2", "N") // "aNbN"Login atau daftar akun gratis untuk membaca cheat sheet ini.