exec Metodu
exec metodu, bir dize üzerinde belirli bir düzenli ifadeye göre arama yapar. Sonuç olarak bulunan alt dize ve onun grupları (capturing groups) döndürülür. Ayrıca, bu metodun her bir sonraki çağrısı, bir önceki bulunan alt dizenin bittiği yerden aramaya başlayacaktır. Eğer eşleşme bulunamazsa - null döndürülür.
Sözdizimi
javascriptduzenli_ifade.exec(dize);
Örnek
Metodun çalışmasını kontrol edelim:
javascriptlet str = '12 34 56';
let reg = /\d+/g;
let res1 = reg.exec(str);
console.log(res1);
let res2 = reg.exec(str);
console.log(res2);
let res3 = reg.exec(str);
console.log(res3);
let res4 = reg.exec(str);
console.log(res4);
Kodun çalıştırılmasının sonucu:
javascript[12]
[34]
[56]
null
Örnek
Metodu bir döngü içinde kullanalım:
javascriptlet str = '12 34 56';
let reg = /\d+/g;
let res;
while (res = reg.exec(str)) {
console.log(res);
}
Kodun çalıştırılmasının sonucu:
javascript[12]
[34]
[56]
Örnek
Bulunan eşleşmeler gruplara ayrılabilir:
javascriptlet str = '12 34 56';
let reg = /(\d)(\d)/g;
let res;
while (res = reg.exec(str)) {
console.log(res);
}
Kodun çalıştırılmasının sonucu:
javascript[12, 1, 2]
[34, 3, 4]
[56, 5, 6]
Örnek
lastIndex özelliği kullanılarak
aranmaya başlanacak konum belirlenebilir:
javascriptlet str = '12 34 56';
let reg = /\d+/g;
reg.lastIndex = 2;
let res1 = reg.exec(str)
console.log(res1);
let res2 = reg.exec(str)
console.log(res2);
Kodun çalıştırılmasının sonucu:
javascript[34]
[56]
Örnek
y değiştiricisi kullanılarak
arama başlangıç konumu sabitlenebilir:
javascriptlet str = '12 34 56';
let reg = /\d+/y;
reg.lastIndex = 2;
let res1 = reg.exec(str)
console.log(res1);
let res2 = reg.exec(str)
console.log(res2);
Kodun çalıştırılmasının sonucu:
javascriptnull
[12]