JavaScript Regular Expression


자바스크립트의 정규표현식(Regular Expression, RegExp)은 문자열에서 패턴을 찾거나 교체하는 데 사용됩니다. 정규표현식은 슬래시(/)로 감싸서 리터럴로 작성하거나 RegExp 객체를 사용하여 생성할 수 있습니다.

리터럴 표기법: 슬래시(/)로 감싸서 표현합니다.

const regex = /pattern/flags;

객체 생성: RegExp 생성자를 사용하여 정규표현식을 만듭니다.

const regex = new RegExp('pattern', 'flags');

플래그(Flags)는 정규표현식의 동작을 제어합니다.

  • g: 전역 검색, 문자열 내 모든 패턴을 찾습니다.
  • i: 대소문자 구분 없이 검색합니다.
  • m: 여러 줄 모드, ^$가 각 줄의 시작과 끝을 의미합니다.
  • s: 점(.)이 줄바꿈 문자를 포함한 모든 문자를 매칭합니다.
  • u: 유니코드 모드, 유니코드 문자를 처리합니다.
  • y: 처음부터 매칭, 검색이 시작된 위치에서만 패턴을 찾습니다.

기본 메타문자는 다음과 같습니다:

  • .: 줄바꿈 문자를 제외한 모든 문자와 매칭
  • ^: 문자열의 시작 부분과 매칭
  • $: 문자열의 끝 부분과 매칭
  • *: 앞 문자가 0번 이상 반복됨
  • +: 앞 문자가 1번 이상 반복됨
  • ?: 앞 문자가 0번 또는 1번 나타남
  • |: OR 연산자
  • (): 그룹화, 하위 표현식을 그룹으로 처리
  • []: 문자 클래스, 대괄호 안에 있는 문자 중 하나와 매칭
  • {}: 수량자, 앞 문자의 반복 횟수를 지정

이스케이프 문자는 메타문자를 일반 문자로 해석합니다.

  • \ : 메타문자를 일반 문자로 해석
  • \d: 숫자와 매칭 (0-9)
  • \D: 숫자가 아닌 것과 매칭
  • \w: 단어 문자와 매칭 (알파벳 대소문자, 숫자, 언더스코어)
  • \W: 단어 문자가 아닌 것과 매칭
  • \s: 공백 문자와 매칭 (스페이스, 탭, 줄 바꿈)
  • \S: 공백 문자가 아닌 것과 매칭
  • \b: 단어 경계와 매칭
  • \B: 단어 경계가 아닌 것과 매칭

기본 패턴 매칭 예제:

const regex = /hello/;
console.log(regex.test("hello world")); // true

대소문자 무시 매칭 예제:

const regex = /hello/i;
console.log(regex.test("Hello World")); // true

전역 검색 예제:

const regex = /hello/g;
const str = "hello world, hello universe";
const matches = str.match(regex);
console.log(matches); // ['hello', 'hello']

숫자 찾기 예제:

const regex = /\d+/g;
const str = "There are 123 apples and 456 oranges.";
const matches = str.match(regex);
console.log(matches); // ['123', '456']

문자열 교체 예제:

const str = "Hello world";
const newStr = str.replace(/world/, "there");
console.log(newStr); // "Hello there"

문자 클래스 예제:

const regex = /[aeiou]/g;
const str = "Hello World";
const matches = str.match(regex);
console.log(matches); // ['e', 'o', 'o']

수량자 예제:

const regex = /\d{3}/g;
const str = "My phone number is 123-456-7890.";
const matches = str.match(regex);
console.log(matches); // ['123', '456', '789']

그룹화와 역참조 예제:

const regex = /(hello) \1/;
console.log(regex.test("hello hello")); // true

비탐욕적 매칭 예제:

const regex = /".*?"/g;
const str = 'He said "hello" and then "goodbye".';
const matches = str.match(regex);
console.log(matches); // ['"hello"', '"goodbye"']

인덱스 찾기 예제:

const regex = /world/;
const str = "Hello world";
const match = regex.exec(str);
console.log(match.index); // 6

이메일 검증 예제:

const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
console.log(emailRegex.test("example@example.com")); // true
console.log(emailRegex.test("invalid-email")); // false

URL 검증 예제:

const urlRegex = /^(https?:\/\/)?([\da-z.-]+)\.([a-z.]{2,6})([/\w .-]*)*\/?$/;
console.log(urlRegex.test("https://www.example.com")); // true
console.log(urlRegex.test("ftp://example.com")); // false

전화번호 검증 예제:

const phoneRegex = /^\+?(\d{1,3})?[-.\s]?(\d{1,4})[-.\s]?(\d{1,4})[-.\s]?(\d{1,9})$/;
console.log(phoneRegex.test("+1-800-555-1234")); // true
console.log(phoneRegex.test("123-4567-890")); // true
console.log(phoneRegex.test("123-45-67890")); // false

이와 같은 예제들을 통해 정규표현식을 다양한 상황에서 어떻게 활용할 수 있는지 이해할 수 있습니다. 정규표현식은 문자열 처리를 매우 강력하고 유연하게 만들어 줍니다. 충분한 연습을 통해 복잡한 패턴을 작성하고 응용할 수 있을 것입니다.


Leave a Reply

Your email address will not be published. Required fields are marked *