
정규표현식(Regular Expressions, RegEx)은 문자열에서 특정 패턴을 검색하거나 매칭하고, 변환하는 데 사용하는 강력한 도구이다. 자바스크립트에서 자주 사용되는 정규표현식 예제를 살펴보자.
진부하지만 이게 어디서 나왔고 어떻게 썼는지 알고는 써야한다고 생각한다.
그러니 간단하게 세줄요약으로 역사를 살펴보자
정규표현식은 패턴과 선택적으로 사용할 수 있는 플래그 i, g, m, u, s, y로 구성된다.
i : 대소문자 구분 없이 검색
const regex = /hello/i;
console.log(regex.test("Hello")); // true
console.log(regex.test("hello")); // true
g : 패턴과 일치하는 모든 것을 검색. g 플래그가 없으면 패턴과 일치하는 첫번째만 리턴
const regex = /o/g;
console.log("hello world".match(regex)); // ["o", "o"]
m : multiline(다중 행) 모드 활성
const regex = /^hello/m;
console.log("hello\nworld".match(regex)); // ["hello"]
u : 유니코드 전체 지원
const regex = /\u{1F600}/u;
console.log(regex.test("😀")); // true
s : .(dot)이 개행 문자 \n도 포함하도록 동작
const regex = /.+/s;
console.log(regex.test("hello\nworld")); // true
y : 문자열의 현재 위치부터 패턴을 매칭. 매칭 실패하면 검색을 중단
const regex = /hello/y;
regex.lastIndex = 6; // 문자열의 6번째 위치에서 검색 시작
console.log(regex.test("hello hello")); // true
console.log(regex.test("hello hello")); // false (이후 위치에서 매칭 안 됨)
여러 플래그들을 조합하여 사용할 수 있다.
const regex = /hello/gi; // 대소문자 구분 없이(global) "hello" 검색
console.log("Hello hello HELLO".match(regex)); // ["Hello", "hello", "HELLO"]
^: 문자열 시작
$: 문자열 끝
.: 임의의 한 문자
*: 0회 이상 반복
+: 1회 이상 반복
?: 0회 또는 1회
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const isValidEmail = emailRegex.test("example@test.com"); // true
const urlRegex = /^(https?:\/\/)?([\da-z.-]+)\.([a-z.]{2,6})([/\w .-]*)*\/?$/;
const isValidUrl = urlRegex.test("https://example.com"); // true
const phoneRegex = /^\+?\d{1,4}?[-.\s]?(\d{1,3}[-.\s]?){1,4}$/;
const isValidPhone = phoneRegex.test("+1 123-456-7890"); // true
const text = " Hello World! ";
const trimmed = text.replace(/^\s+|\s+$/g, ""); // "Hello World!"
const log = "2024-11-19 Error: Something went wrong";
const dateRegex = /\d{4}-\d{2}-\d{2}/;
const date = log.match(dateRegex)[0]; // "2024-11-19"
const text = "Order ID: 12345";
const numbers = text.match(/\d+/g); // ["12345"]
const str = "JavaScript is amazing";
const wordRegex = /amazing/;
const hasWord = wordRegex.test(str); // true
정규표현식은 복잡해서 처음엔 어렵게 느껴질 수 있지만 텍스트 처리나 데이터 검증 같은 다양한 곳에서 정말 많이 쓰이고 있다. 모든 패턴을 외울 필요는 없으나 자주 쓰는 기본 패턴 몇 개 정도는 외워두면 실무에서 꽤 유용하다. 특히 이메일 검증, 공백 제거, 특정 문자열 검색 같은 건 알아두면 쓸 일이 많다.
끝