정규표현식을 응용하는 방법에는 다양한 사례가 있습니다. 아래 몇 가지 유용한 응용 예시를 소개합니다.
const emailRegex = /^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/;
const isValidEmail = emailRegex.test("example@mail.com"); // true 또는 false 반환
const str = "Hello, World!";
const newStr = str.replace(/World/, "Regex");
// newStr: "Hello, Regex!"
const csv = "John,Jane,Doe";
const names = csv.split(/,\s*/);
// names: ["John", "Jane", "Doe"]
g
플래그를 사용해 문자열 내의 모든 매칭 항목을 배열로 반환합니다.const text = "The rain in Spain stays mainly in the plain.";
const matches = text.match(/ain/g);
// matches: ["ain", "ain", "ain", "ain"]
const html = "<div>Content</div>";
const tagRegex = /<(\w+)>.*<\/\1>/;
const result = html.match(tagRegex);
// result[1]는 "div"가 됩니다.
const dateStr = "2025-04-09";
// 연-월-일을 월/일/연도로 변환 (간단한 예시)
const formattedDate = dateStr.replace(/(\d{4})-(\d{2})-(\d{2})/, "$2/$3/$1");
// formattedDate: "04/09/2025"