RegEx-in exec metodu JavaScript
exec metodu setr uzre
axtaris edir. Netice olaraq tapilan
subsetr ve onun qruplari qaytarilir.
Bununla yanaşı, bu metodun her sonrakı
çağırışı axtarisa elaqedar olaraq
evvelki tapılan subsetrin bitdiyi
yerden baslayacaq.
Gelin misala baxaq. Bu setrimiz olsun:
let str = '12 34 56';
Bu regulyar ifademiz olsun:
let reg = /\d+/g;
Gelin metodumuzu setrimiz ucun ardıcıl olaraq çağıraq:
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
Uc çağırışdan sonra, setrimizde
regulyarla uyğunluq olmadığı üçün,
metodun sonrakı çağırışı
null qaytaracaq:
let res4 = reg.exec(str);
console.log(res4); // null
Metodun bu xüsusiyyetini dövrdə istifadə etmek elverişlidir:
let str = '12 34 56';
let reg = /\d+/g;
let res;
while (res = reg.exec(str)) {
console.log(res); // [12], [34], [56]
}
Yalnız uyğunluğu tapmaq deyil, hem de onu qruplara ayırmaq olar:
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]
}
Bu set verilmişdir:
let str = '12:37:57 15:48:58 17:59:59';
Onda vaxt olan butun subsetrleri tapın ve her biri ucun saat, deqiqe ve saniyeleri qruplara ayırın.