24. RegularExpression

효율적인 패턴 매칭과 문자열 처리, 정규표현식

Index

정규 표현식의 목적

정규 표현식의 생성

플래그(Flags)


1. 정규 표현식의 목적

1.1 정규표현식의 생성 목적은 무엇일까

  • 정규표현식(Regular Expression, RegEx)의 핵심은 효율적인 패턴 매칭과 문자열 처리에 있으며, 이를 위해 다양한 최적화 기법과 유연한 패턴 조합 기능이 제공됩니다.

ex_1. 정규표현식 없이 이메일 추출하기

function findEmails(text) {
  let words = text.split(/\s+/); // 공백을 기준으로 단어 분리
  let emails = [];

  for (let word of words) {
    if (word.includes("@") && word.includes(".")) {
      // '@'와 '.'이 포함된 경우 후보로 선정
      let parts = word.split("@");
      if (parts.length === 2 && parts[0] && parts[1]) {
        // '@' 앞뒤에 문자열이 있어야 함
        let domainParts = parts[1].split(".");
        if (domainParts.length > 1 && domainParts.every((part) => part)) {
          // 도메인명 검증
          emails.push(word);
        }
      }
    }
  }
  return emails;
}

// 테스트
let text =
  "Contact me at example@email.com or support@company.org for more info.";
console.log(findEmails(text)); // ["example@email.com", "support@company.org"]


ex_2. 정규표현식을 사용한 이메일 추출

let text =
  "Contact me at example@email.com or support@company.org for more info.";
let pattern = /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g;
console.log(text.match(pattern)); // ["example@email.com", "support@company.org"]
  • 더 짧고, 더 정확한 이메일 매칭 가능.

  • 다양한 이메일 변형을 자동으로 인식.



2. 정규 표현식의 생성

2.1 JavaScript에서 정규표현식을 사용하는 두 가지 방법

2.1.1 RegExp 객체의 메서드

RegExp 자체에서 실행되는 메서드로, 패턴을 검증하거나 특정 매칭을 찾는 용도로 사용됩니다.


2.1.1.1 RegExp.prototype.test()

  • 문자열이 정규 표현식 패턴과 일치하는지 true/false로 변환
let regex = /hello/;
console.log(regex.test("hello world")); // true
console.log(regex.test("hi world")); // false


2.1.1.2 RegExp.prototype.exec()

  • 문자열에서 정규표현식과 일치하는 첫번째 결과를 배열로 변환(null일 수도 있음)
let regex = /hello/;
let result = regex.exec("hello world");
console.log(result[0]); // "hello"


2.1.2 String 객체의 메서드

2.1.2.1 String.prototype.match()

  • 문자열에서 정규표현식과 일치하는 모든 결과를 배열로 반환
  • g플래그(전역검색)를 사용하면 모든 일치 항목을 찾음
let text = "apple banana apple";
let result = text.match(/apple/g);
console.log(result); // ["apple", "apple"]


2.1.2.2 String.prototype.replace()

  • 정규표현식을 이용해 문자열을 변환할 때 사용
let text = "hello world";
let result = text.replace(/hello/, "hi");
console.log(result); // "hi world"


2.1.2.3 String.prototype.search()

  • 문자열에서 정규표현식과 일치하는 첫 번째 위치(인덱스)를 반환
let text = "hello world";
console.log(text.search(/world/)); // 6


2.1.2.4 String.prototype.split()

  • 정규표현식을 사용해 문자열을 특정 패턴 기준으로 나누기
let text = "apple, banana; grape|orange";
let words = text.split(/[,;|]/);
console.log(words); // ["apple", " banana", " grape", "orange"]


🧐 Q. RegExp 객체의 메서드뿐만 아니라 String 객체의 메서드도 함께 소개한 이유는 무엇일까?

  • 정규표현식은 단독(RegExp)으로 사용할 수도 있고, 문자열(String)에서 활용할 수도 있기 때문.
  • test()exec()정규표현식이 주체가 되는 방식.
  • match(), replace(), search(), split()문자열이 주체가 되면서 정규표현식을 활용하는 방식.

💡 즉, 정규표현식을 사용하는 메서드가 꼭 RegExp 객체에서만 존재하는 것이 아니라, String 객체에서도 활용될 수 있기 때문에 함께 설명한 것 🚀



3. 플래그

Photo of flag

Regular Expression flag

Ungmo Lee. (2020). Modern Javascript DeepDive. wikibooks. p.581.

const target = "Is this all there is?";

target.match(/is/);
// target 문자열에서 is 문자열을 대소문자를 구별하여 한 번만 검색한다.
// ["is", index: 5, input: "Is this all there is?", groups: undefined]

target.match(/is/i);
// target 문자열에서 is 문자열을 대소문자를 구별하지 않고 한 번만 검색한다.
// ["Is", index: 0, input: "Is this all there is?", groups: undefined]

target.match(/is/g);
// target 문자열에서 is 문자열을 대소문자를 구별하여 전역 검색한다.
// ["is", "is"]

target.match(/is/gi);
// target 문자열에서 is 문자열을 대소문자를 구별하지 않고 전역 검색한다.
// ["Is", "is"', "is"]




reference: 모던자바스크립트 Deep Dive 31장. 정규표현식 RegExp