자바스크립트/정규표현식

자바스크립트 정규 표현식, exec() 메서드란?

Jake Seo 2023. 3. 6. 19:34

RegExp.prototype.exec() 메서드란?

  • 인자로 받은 문자열 (str) 에서 match 를 찾아내고 result array 혹은 null 을 반환한다.
  • 자바스크립트 정규표현식을 다룰 때 쓴다.

코드 예제

검색 성공 사례

const regex1 = RegExp("foo*", "g");
const str1 = "table football, foosball";
let array1;

while ((array1 = regex1.exec(str1)) !== null) {
  console.log("array1", array1);
  console.log(`Found ${array1[0]}. Next starts at ${regex1.lastIndex}.`);
}

/*
array1 ['foo', index: 6, input: 'table football, foosball', groups: undefined]
"Found foo. Next starts at 9."
*/

/*
array1 ['foo', index: 16, input: 'table football, foosball', groups: undefined]
"Found foo. Next starts at 19."
*/
  • [ 찾아낸 문자열, 시작점 인덱스, 원본 문자열, 그룹 ] 으로 표기된다.
  • 그룹 에 해당하는 부분은 오직 named capturing group 일 때만 유효하다.
  • 예제에서 볼 수 있듯, regex1lastIndex 속성 값도 변화시킨다.
    • 자바스크립트의 RegExp 객체는 stateful 하다는 것을 엿볼 수 있다.

검색 실패 사례

const regex1 = RegExp("foo*", "g");
const str1 = "table sootball, soosball";
let array1;

while ((array1 = regex1.exec(str1)) !== null) {
  console.log("array1", array1);
  console.log(`Found ${array1[0]}. Next starts at ${regex1.lastIndex}.`);
}

console.log("failed. array1", array1);

/*
failed. array1 null
*/
  • 검색 실패 시에는 null 을 반환한다.
반응형