
💡 정규식 안에서 특정 부분을 소괄호
()로 감싸서 기억시키는 기능이다.
즉, 특정 부분을 추출하거나 나중에 다시 참조할 수 있게 만들어주는 것이다.
const str = "이름: 홍길동, 나이: 38";
const regex = /이름: (\w+), 나이: (\d+)/;
const result = str.match(regex);
console.log(result) // ['이름: 홍길동, 나이: 38', '홍길동', '38']
📌 여기서 (\w+)는 문자열을, (\d+)는 숫자를 캡처한 것이다.
result
n번째 캡처 그룹의 값을 반환const address = "iamxunwoo@gmail.com";
const [_, email, domain] = address.match(/(\w+)@(\w+\.\w+)/);
console.log(`email: ${email}, domain: ${domain}`) // email: iamxunwoo, domain: gmail.com
const date = "2025-06-16";
const regex = /(\d{4})-(\d{2})-(\d{2})/;
const formattedDate = date.replace(regex, "/$3/$2/$1");
console.log(formattedDate) // '16/06/2025'
replace() 함수에서 $1, $2, $3은 각각 캡처 그룹을 의미한다.match는 첫 번째 일치 결과만 가져오므로 g 플래그가 있는 경우에는 matchAll()을 사용하는 게 좋다.