정규표현식

Jinmin Kim·2020년 1월 15일
0

정규표현식 응용 예시

정규표현식을 응용하는 방법에는 다양한 사례가 있습니다. 아래 몇 가지 유용한 응용 예시를 소개합니다.

  1. 문자열 검증 (Validation):
    • 이메일, 전화번호, 우편번호 등의 형식을 검사할 때 사용합니다.
    • 예시 (이메일 검사):
const emailRegex = /^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/;
const isValidEmail = emailRegex.test("example@mail.com"); // true 또는 false 반환
  1. 문자열 치환 (Replacement):
    • 문자열 내 특정 패턴을 찾아 다른 문자열로 치환합니다.
    • 예시:
const str = "Hello, World!";
const newStr = str.replace(/World/, "Regex");
// newStr: "Hello, Regex!"
  1. 문자열 분리 (Splitting):
    • 여러 구분자(콤마, 공백 등)를 사용해 문자열을 배열로 분리합니다.
    • 예시:
      const csv = "John,Jane,Doe";
      const names = csv.split(/,\s*/);
      // names: ["John", "Jane", "Doe"]
      
  2. 반복 패턴 찾기 (Matching multiple occurrences):
    • g 플래그를 사용해 문자열 내의 모든 매칭 항목을 배열로 반환합니다.
    • 예시:
      const text = "The rain in Spain stays mainly in the plain.";
      const matches = text.match(/ain/g);
      // matches: ["ain", "ain", "ain", "ain"]
      
  3. 캡처 그룹 및 재참조 (Capture Groups & Backreferences):
    • 특정 부분을 캡처하여 재사용하거나, 패턴 내에서 동일한 값을 반복 검사할 때 사용합니다.
    • 예시 (HTML 태그 추출):
      const html = "<div>Content</div>";
      const tagRegex = /<(\w+)>.*<\/\1>/;
      const result = html.match(tagRegex);
      // result[1]는 "div"가 됩니다.
      
  4. 문자열 포맷 변환:
    • 날짜, 시간, 숫자 포맷을 변경하거나, 특정 형식으로 변환할 때 사용합니다.
    • 예시:
      const dateStr = "2025-04-09";
      // 연-월-일을 월/일/연도로 변환 (간단한 예시)
      const formattedDate = dateStr.replace(/(\d{4})-(\d{2})-(\d{2})/, "$2/$3/$1");
      // formattedDate: "04/09/2025"
      
profile
Let's do it developer

0개의 댓글