exec 메서드
exec 메서드는 주어진 정규 표현식을 사용하여 문자열을 검색합니다. 결과로 발견된 부분 문자열과 그 캡처 그룹이 반환됩니다. 이때, 이 메서드의 각 후속 호출은 이전에 발견된 부분 문자열이 끝난 위치부터 검색을 시작합니다. 일치하는 항목이 없으면 null이 반환됩니다.
구문
정규_표현식.test(문자열);
예제
메서드의 작동을 확인해 보겠습니다:
let 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);
코드 실행 결과:
[12]
[34]
[56]
null
예제
루프에서 메서드를 사용해 보겠습니다:
let str = '12 34 56';
let reg = /\d+/g;
let res;
while (res = reg.exec(str)) {
console.log(res);
}
코드 실행 결과:
[12]
[34]
[56]
예제
발견된 일치 항목을 캡처 그룹으로 분해할 수 있습니다:
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]
예제
lastIndex 속성을 사용하여 검색을 시작할 위치를 지정할 수 있습니다:
let 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);
코드 실행 결과:
[34]
[56]
예제
수정자 y를 사용하여 검색 시작 위치를 고정할 수 있습니다:
let 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);
코드 실행 결과:
null
[12]