JavaScript ရှိ ရီဂျက်စ် ဖော်မြူလာများတွင် exec method အသုံးပြုခြင်း
exec method သည် string တစ်ခုအတွင်းရှိ ကိုက်ညီမှုများကို ရှာဖွေပေးပါသည်။ ရလဒ်အဖြစ် တွေ့ရှိရသော substring နှင့် ၎င်း၏ capturing groups များကို ပြန်ပေးသည်။ ထို့အပြင် ဤ method ကို နောက်တစ်ကြိမ် ထပ်မံခေါ်သုံးတိုင်းတွင် ယခင်တွေ့ရှိပြီးသော substring ၏ နေရာမှ စတင်၍ ရှာဖွေမှု ပြုလုပ်ပါသည်။
ဥပမာတစ်ခုဖြင့် ကြည့်ရှုကြပါစို့။ ကျွန်ုပ်တို့တွင် အောက်ပါ string တစ်ခုရှိသည်ဆိုပါစို့:
let str = '12 34 56';
ကျွန်ုပ်တို့တွင် အောက်ပါ ရီဂျက်စ် ဖော်မြူလာ တစ်ခုရှိသည်ဆိုပါစို့:
let reg = /\d+/g;
ယခု ကျွန်ုပ်တို့၏ method ကို ကျွန်ုပ်တို့၏ string အတွက် အစဉ်လိုက် ခေါ်ယုံကြည့်ကြပါမည်:
let res1 = reg.exec(str);
console.log(res1[0]); // 12
let res2 = reg.exec(str);
console.log(res2[0]); // 34
let res3 = reg.exec(str);
console.log(res3[0]); // 56
အကြိမ်သုံးကြိမ်ခေါ်ပြီးနောက်၊ ကျွန်ုပ်တို့၏ string တွင် ရီဂျက်စ် ဖော်မြူလာနှင့် ကိုက်ညီမှုများ မရှိတော့သောကြောင့်၊ နောက်ထပ် method ခေါ်ယုံသည်
null ကို ပြန်ပေးပါမည်:
let res4 = reg.exec(str);
console.log(res4); // null
Method ၏ ထိုသတ်သတ်မှတ်မှတ် လက္ခဏာကို loop အတွင်း အသုံးပြုရန် အဆင်ပြေပါသည်:
let str = '12 34 56';
let reg = /\d+/g;
let res;
while (res = reg.exec(str)) {
console.log(res); // [12], [34], [56]
}
ကိုက်ညီမှုကို တွေ့ရှိရုံသာမက၊ ၎င်းကို capturing groups များအဖြစ် ခွဲထုတ်နိုင်ပါသည်:
let str = '12 34 56';
let reg = /(\d)(\d)/g;
let res;
while (res = reg.exec(str)) {
console.log(res); // [12, 1, 2], [34, 3, 4], [56, 5, 6]
}
အောက်ပါ string ကို ပေးထားပါသည်:
let str = '12:37:57 15:48:58 17:59:59';
၎င်းအတွင်းရှိ အချိန်ပြသော substring အားလုံးကို ရှာဖွေပြီး၊ တွေ့ရှိသည်တိုင်း နာရီ၊ မိနစ်၊ စက္ကန့်များကို capturing groups များအဖြစ် ခွဲထုတ်ပါ။