Regular Expression — asoslar va amaliyot

~25 daq · JavaScript · Ilg'or mavzular

Muammodan boshlaylik

Email tekshirishingiz kerak. Foydalanuvchi kiritgani to'g'ri formatdami?

includes("@") — @ bor-yo'qligini tekshiradi. Lekin @ bor bo'lishi yetarli emas — @ siz boshqa belgi ham bo'lishi kerak, domenda nuqta kerak, va hokazo.

startsWith, endsWith, split bilan bu qoidalarni yozish qiyinlashib ketadi. Ko'p shart, ko'p tekshiruv.

Regular Expression — matnda pattern (namuna) qidirish uchun til. Bir qatorda ko'p qoidalarni ifodalash mumkin.


Regular Expression nima?

Regex — matn uchun "qolip". "Mana shu naqshga mos matn bor-yo'qligini tekshir" degan buyruq.

Hayotiy o'xshatma

Pochta xodimi va konvert shakli. Konvert qabul qilinishi uchun: manzil bo'lishi kerak, shahar va indeks bo'lishi kerak, ma'lum o'lchamdan kichik bo'lmasligi kerak. Xodim har konvertni bu qolipga solishtiradi — mos kelsa qabul qiladi.

Regex — o'sha qolip. Matn — konvert. test() — qolipga mos keladimi tekshirish.


Regex yaratish

Ikki usul:

// 1. Literal — /pattern/flags
const regex1 = /jasur/i;

// 2. Konstruktor — dinamik pattern uchun
const so'z   = "jasur";
const regex2 = new RegExp(so'z, "i");

Literal usul — tez, ko'p ishlatiladi. Konstruktor — pattern o'zgaruvchidan keladigan bo'lsa.


Eng oddiy pattern — belgilar

Oddiy belgilar o'z-o'ziga mos keladi:

const regex = /jasur/;

regex.test("Jasur yaxshi dasturchi");  // false — katta harf farq qiladi
regex.test("jasur yaxshi dasturchi");  // true

i flagi — katta-kichik harfga e'tibor bermaslik:

const regex = /jasur/i;

regex.test("Jasur yaxshi dasturchi"); // true ← i flag tufayli
regex.test("JASUR ISHLAMOQDA");       // true

Maxsus belgilar — pattern tili

Regex ning kuchi — maxsus belgilarda. Ular aniq belgi emas, qoida ifodalaydi.

. — istalgan bitta belgi (yangi qator emas)

/j.sur/.test("jasur");  // true — . = a
/j.sur/.test("josur");  // true — . = o
/j.sur/.test("jsur");   // false — . bitta belgi bo'lishi shart

^ — matn boshi, $ — matn oxiri

/^salom/.test("salom dunyo"); // true — boshida "salom"
/^salom/.test("dunyo salom"); // false — boshida emas

/dunyo$/.test("salom dunyo"); // true — oxirida "dunyo"
/^salom$/.test("salom");      // true — faqat "salom", boshqa yo'q
/^salom$/.test("salom dunyo"); // false — oxirida boshqa narsa bor

^ va $ — "faqat shu, boshqa yo'q" kafolati. Emailni tekshirganda muhim: faqat email bo'lsin, oldin/keyin boshqa narsa bo'lmasin.

* — 0 yoki ko'p, + — 1 yoki ko'p, ? — 0 yoki 1

/go*gle/.test("ggle");   // true — o = 0 ta
/go*gle/.test("google"); // true — o = 2 ta
/go*gle/.test("gogle");  // true — o = 1 ta

/go+gle/.test("ggle");   // false — + kamida 1 ta
/go+gle/.test("google"); // true

/colou?r/.test("color");  // true — u = 0 ta
/colou?r/.test("colour"); // true — u = 1 ta

{n}, {n,m} — aniq miqdor

/\d{4}/.test("2026");    // true — 4 ta raqam
/\d{4}/.test("202");     // false — 4 ta emas

/\d{2,4}/.test("20");    // true — 2 ta (2 dan 4 gacha)
/\d{2,4}/.test("2026");  // true — 4 ta
/\d{2,4}/.test("202678"); // true — ichida 4 ta topildi

Character classes — belgi guruhlari

\d — raqam (0-9)

/\d/.test("abc3def"); // true — 3 topildi
/\d/.test("abcdef");  // false — raqam yo'q

\w — harf, raqam yoki pastki chiziq ([a-zA-Z0-9_])

/\w+/.test("jasur_25"); // true

\s — bo'sh joy (space, tab, yangi qator)

/\s/.test("jasur malika"); // true — o'rtada bo'sh joy
/\s/.test("jasurmalika");  // false

\D, \W, \S — teskarisi

\D — raqam emas, \W — \w emas, \S — bo'sh joy emas.

[...] — to'plam ichidan biri

/[aeiou]/.test("salom"); // true — "a" va "o" bor
/[aeiou]/.test("srvs");  // false — unli yo'q

/[a-z]/.test("Jasur");   // true — kichik "asur" bor
/[A-Z]/.test("jasur");   // false — katta harf yo'q
/[0-9]/.test("abc5");    // true — 5 bor

/[^aeiou]/.test("salom"); // true — ^ ichida = "bu emas": undoshlar bor

Guruhlash — ()

() — bir nechta belgini guruhga birlashtirish:

/(ha)+/.test("hahaha"); // true — "ha" bir yoki ko'p marta
/(ha)+/.test("ha");     // true
/(ha)+/.test("h");      // false

Flaglar

Flag Nima qiladi
i Katta-kichik harfga e'tiborsiz
g Barcha moslarni topish (birinchisi emas)
m ^ va $ — har qator boshi/oxiri

Metodlar — qanday ishlatiladi

regex.test(matn) — bormi yo'qmi

/\d{4}/.test("2026"); // true
/\d{4}/.test("abc");  // false

matn.match(regex) — topilganlarni qaytarish

const matn = "Telefon: +998901234567 yoki +998712345678";

// g flagi yo'q — faqat birinchi topilgan
matn.match(/\+998\d{9}/);
// ["+998901234567", ...meta...]

// g flag bilan — hammasi
matn.match(/\+998\d{9}/g);
// ["+998901234567", "+998712345678"]

matn.replace(regex, yangi) — almashtirish

"  jasur  malika  ".replace(/\s+/g, " ").trim();
// "jasur malika" ← ko'p bo'sh joylar bitta bo'sh joyga

"parol: 12345".replace(/\d+/, "***");
// "parol: ***" ← raqamlar yashirildi

matn.split(regex) — bo'lish

"jasur, malika;  sardor  ".split(/[,;]\s*/);
// ["jasur", "malika", "sardor"] ← vergul yoki nuqtali verguldan bo'ldi

Amaliy misollar — asosiy tekshiruvlar

Email tekshirish

function emailToGrimi(email) {
  const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return regex.test(email);
}

emailToGrimi("jasur@mail.com");    // true
emailToGrimi("jasur@mail.com.uz"); // true
emailToGrimi("jasur@");            // false
emailToGrimi("jasurmail.com");     // false
emailToGrimi("jas ur@mail.com");   // false — bo'sh joy bor

Pattern tushuntirish:

  • ^ — boshidan
  • [^\s@]+ — bo'sh joy va @ bo'lmagan bir yoki ko'p belgi
  • @ — @ belgisi
  • [^\s@]+ — domen nomi
  • \. — nuqta (backslash — chunki . maxsus belgi)
  • [^\s@]+ — domen kengaytmasi
  • $ — oxirigacha

Parol kuchi tekshirish

function parolKuchli(parol) {
  const kamidaSakkiz  = /.{8,}/;
  const kattaHarf     = /[A-Z]/;
  const kichikHarf    = /[a-z]/;
  const raqam         = /\d/;
  const maxsusBeigi   = /[!@#$%^&*]/;

  return (
    kamidaSakkiz.test(parol) &&
    kattaHarf.test(parol)    &&
    kichikHarf.test(parol)   &&
    raqam.test(parol)
  );
}

parolKuchli("abc123");      // false — katta harf yo'q, qisqa
parolKuchli("Abc12345");    // true
parolKuchli("qisqa");       // false

O'zbekiston telefon raqami

function telefonToGrimi(tel) {
  // +998 yoki 998 yoki 0 bilan boshlanishi, keyin 9 ta raqam
  const regex = /^(\+998|998|0)\d{9}$/;
  return regex.test(tel.replace(/[\s\-]/g, "")); // bo'sh joy va tire olib tashlanadi
}

telefonToGrimi("+998901234567"); // true
telefonToGrimi("998901234567");  // true
telefonToGrimi("0901234567");    // true
telefonToGrimi("901234567");     // false

Tez-tez uchraydigan xatolar

. belgisini escape qilmaslik:

// ❌ — . = istalgan belgi, nafaqat nuqta
/jasur.mail.com/.test("jasurXmailYcom"); // true — xato!

// ✅ — \. = aniq nuqta
/jasur\.mail\.com/.test("jasurXmailYcom"); // false
/jasur\.mail\.com/.test("jasur.mail.com"); // true

g flagi bilan test() — tushunarsiz holat:

g flagi bilan regex ob'ekti lastIndex ni eslab qoladi. Bir xil regex ob'ektida test() ni qayta chaqirish — oldingi o'rından davom etadi:

const regex = /\d/g;

regex.test("abc1def2"); // true — 1 topildi (lastIndex = 4)
regex.test("abc1def2"); // true — 2 topildi (lastIndex = 8)
regex.test("abc1def2"); // false — oxiriga yetdi, qaytadan boshidan

// ✅ — har safar yangi regex yoki lastIndex = 0
/\d/.test("abc1def2"); // literal har safar yangi — muammo yo'q

Murakkab regex — o'qish qiyin:

// ❌ — bir qatorda, tushunarsiz
const r = /^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)[A-Za-z\d@$!%*?&]{8,}$/;

// ✅ — alohida tekshiruvlar, izohli
function tekshir(parol) {
  return (
    parol.length >= 8     &&   // kamida 8 belgi
    /[A-Z]/.test(parol)  &&   // katta harf
    /[a-z]/.test(parol)  &&   // kichik harf
    /\d/.test(parol)           // raqam
  );
}

Xulosa

Regex — matnda pattern qidirish tili. Murakkab ko'rinsa ham — asosiy belgilarni bilish amaliyotning 90%ini qoplaydi.

Eng ko'p ishlatiladiganlar:

  • \d — raqam, \w — so'z belgisi, \s — bo'sh joy
  • + — biri yoki ko'p, * — nol yoki ko'p, ? — nol yoki bir
  • ^ — bosh, $ — oxir
  • [a-z] — to'plam, [^...] — bundan tashqari
  • {n,m} — aniq miqdor

Metodlar: test() — bormi/yo'qmi, match() — topilganlar, replace() — almashtirish.


Keyingi dars

65-dars: Garbage Collection — xotira qanday tozalanadi, Memory Leak