
정규 표현식은 짧고 간결한 표현으로 문자열에서 특정 패턴을 효율적으로 검색, 조작, 검증할 수 있기 때문에 코드의 길이를 줄이는데 효과적이다. 이번 포스팅을 통해 제대로 정리하고 넘어가보자.
정규 표현식(regular expression, regex)은 일정한 패턴을 가진 문자열의 집합을 표현하기 위해 사용하는 형식 언어(formal language)다.
정규 표현식은 패턴과 플래그로 구성된다.
/pattern/flags
i (Ignore case): 대소문자를 구별하지 않고 패턴을 검색한다.g (Global): 대상 문자열 내에서 패턴과 일치하는 모든 문자열을 전역 검색한다.m (Multi line): 문자열의 행이 바뀌더라도 패턴 검색을 계속한다.s (Dotall): 점(.)이 개행 문자(\n)도 포함하여 일치하도록 만든다.y (Sticky): 지정된 위치에서부터만 검색을 시작한다.u (Unicode): 유니코드 전체 문자 지원을 활성화한다./로 열고 닫으며 문자열의 따옴표는 생략한다..: 임의의 문자 한 개를 의미한다. 개행 문자(\n)를 제외한 모든 문자에 일치한다.\d: 숫자(0-9)를 의미한다.\D: 숫자가 아닌 문자를 의미한다.\w: 알파벳, 숫자, 언더스코어를 의미한다. (a-z, A-Z, 0-9, _)\W: 알파벳, 숫자, 언더스코어가 아닌 문자를 의미한다.\s: 공백 문자(띄어쓰기, 탭, 개행)를 의미한다.\S: 공백이 아닌 문자를 의미한다.^:[...]내의 ^은 not의 의미를 갖고, [...] 밖의 ^은 문자열의 시작을 의미한다.$: 문자열의 끝을 의미한다.\b: 단어 경계를 나타낸다.\B: 단어 경계가 아님을 나타낸다.*: 0회 이상 반복 (ex. a*는 a가 0번 이상 반복되는 경우)+: 1회 이상 반복 (ex. a+는 a가 1번 이상 반복되는 경우)?: 0회 또는 1회 등장 (ex. a?는 a가 0번 또는 1번만 있는 경우){n}: 정확히 n회 반복 (ex. a{3}는 aaa에만 일치){n,}: 최소 n회 반복 (ex. a{2,}는 aa, aaa 등에 일치){n,m}: 최소 n회, 최대 m회 반복 (ex. a{1,3}는 a, aa, aaa에만 일치)(abc) 그룹을 지정하여 abc에 일치하도록 만든다.|: or의 의미를 갖는다. (ex. a|b는 a또는 b에 일치)[]: [] 내의 문자는 or로 동작한다. 범위를 지정하려면 []내에 -를 사용한다.(?:...): 캡처하지 않는 그룹을 만든다.RegExp객체의 메서드와 String 메서드로 나눌 수 있다.null을 반환한다.const numberPattern = /\d+/;
const text = "I have 2 cats and 3 dogs.";
const result = numberPattern.exec(text);
console.log(result[0]); // "2" (첫 번째로 발견된 숫자)
const hasNumber = /\d/;
console.log(hasNumber.test("Hello123")); // true (숫자가 있음)
console.log(hasNumber.test("HelloWorld")); // false (숫자가 없음)
const text = "There are 42 apples and 19 oranges.";
const numbers = text.match(/\d+/g);
console.log(numbers); // ["42", "19"]
const sentence = "Hello World! How are you?";
const noSpaces = sentence.replace(/\s/g, '');
console.log(noSpaces); // "HelloWorld!Howareyou?"
const sentence = "I am learning JavaScript. JavaScript is fun!";
const wordPosition = sentence.search(/JavaScript/);
console.log(wordPosition); // 14 (첫 번째 "JavaScript"의 시작 위치)
const sentence = "Learning JavaScript is fun!";
const words = sentence.split(/\s/);
console.log(words); // ["Learning", "JavaScript", "is", "fun!"]
// 이메일 유효성 검사
const emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
console.log(emailPattern.test('example@example.com')); // true
// 모든 숫자 찾기
const text = "There are 42 apples and 19 oranges.";
const numberPattern = /\d+/g;
console.log(text.match(numberPattern)); // ["42", "19"]
// 공백 제거
const sentence = " Hello World! ";
const trimPattern = /^\s+|\s+$/g;
console.log(sentence.replace(trimPattern, '')); // "Hello World!"