정규 표현식 기초 — 패턴 문법, 플래그, 실전 매칭 예제
정규 표현식(RegExp)은 처음 보면 암호 같지만, 패턴을 하나씩 익히면 문자열 처리에서 강력한 도구가 됩니다. 면접에서 직접 정규식을 작성하라는 문제가 나오기도 하니, 기본 문법은 확실히 잡아두는 게 좋습니다.
정규식 만들기
// 리터럴 방식 (더 많이 쓰임)
const regex1 = /hello/;
// 생성자 방식 (동적 패턴에 유용)
const regex2 = new RegExp("hello");
// 동적 패턴 예시
const searchTerm = "자바스크립트";
const dynamicRegex = new RegExp(searchTerm, "gi");
기본 메서드
const regex = /hello/;
// test — 매칭 여부 (boolean)
regex.test("hello world"); // true
regex.test("Hi there"); // false
// exec — 매칭 결과 (상세 정보)
regex.exec("hello world");
// ["hello", index: 0, input: "hello world", groups: undefined]
// 문자열 메서드와 함께
"hello world".match(/hello/); // ["hello"]
"hello world".search(/world/); // 6 (인덱스)
"hello world".replace(/world/, "JS"); // "hello JS"
문자 클래스
// \d — 숫자 (= [0-9])
/\d/.test("abc3"); // true
// \w — 단어 문자 (= [A-Za-z0-9_])
/\w/.test("hello"); // true
// \s — 공백 문자 (스페이스, 탭, 줄바꿈)
/\s/.test("hello world"); // true
// 대문자 = 반대
// \D — 숫자가 아닌 것
// \W — 단어 문자가 아닌 것
// \S — 공백이 아닌 것
// . — 줄바꿈을 제외한 모든 문자
/./.test("a"); // true
/./.test("\n"); // false
수량자
// * — 0개 이상
/ab*c/.test("ac"); // true (b가 0개)
/ab*c/.test("abbc"); // true (b가 2개)
// + — 1개 이상
/ab+c/.test("ac"); // false (b가 0개)
/ab+c/.test("abc"); // true
// ? — 0개 또는 1개
/colou?r/.test("color"); // true
/colou?r/.test("colour"); // true
// {n} — 정확히 n개
/\d{3}/.test("123"); // true
/\d{3}/.test("12"); // false
// {n,m} — n개 이상 m개 이하
/\d{2,4}/.test("1"); // false
/\d{2,4}/.test("12"); // true
/\d{2,4}/.test("12345"); // true (1234가 매칭)
// {n,} — n개 이상
/\d{3,}/.test("12345"); // true
앵커와 경계
// ^ — 문자열/줄 시작
/^hello/.test("hello world"); // true
/^hello/.test("say hello"); // false
// $ — 문자열/줄 끝
/world$/.test("hello world"); // true
/world$/.test("world cup"); // false
// ^와 $ 조합 — 전체 매칭
/^\d{3}$/.test("123"); // true
/^\d{3}$/.test("1234"); // false
// \b — 단어 경계
/\bcat\b/.test("cat"); // true
/\bcat\b/.test("category"); // false
/\bcat\b/.test("the cat sat"); // true
그룹과 대안
// () — 캡처 그룹
const match = "2026-03-28".match(/(\d{4})-(\d{2})-(\d{2})/);
console.log(match[1]); // "2026" (년)
console.log(match[2]); // "03" (월)
console.log(match[3]); // "28" (일)
// | — OR
/cat|dog/.test("I have a cat"); // true
/cat|dog/.test("I have a dog"); // true
// (?:) — 비캡처 그룹
/(?:http|https):\/\//.test("https://example.com"); // true
플래그
// g — 전역 검색 (모든 매칭)
"aaa".match(/a/); // ["a"] (첫 번째만)
"aaa".match(/a/g); // ["a", "a", "a"] (모두)
// i — 대소문자 무시
/hello/i.test("Hello"); // true
// m — 멀티라인 (^와 $가 각 줄에 적용)
const text = "line1\nline2\nline3";
text.match(/^line/gm); // ["line", "line", "line"]
// s — dotAll (.이 줄바꿈도 매칭)
/a.b/.test("a\nb"); // false
/a.b/s.test("a\nb"); // true
문자 집합
// [abc] — a, b, c 중 하나
/[aeiou]/.test("hello"); // true (e가 매칭)
// [a-z] — 범위
/[a-z]/.test("Hello"); // true (e가 매칭)
/[A-Z]/.test("hello"); // false
// [^abc] — a, b, c를 제외한 모든 문자
/[^0-9]/.test("abc"); // true (숫자가 아닌 문자 존재)
/[^0-9]/.test("123"); // false
자주 쓰이는 실전 패턴
// 이메일 (간이 검증)
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
emailRegex.test("user@example.com"); // true
// 휴대폰 번호 (한국)
const phoneRegex = /^01[016789]-?\d{3,4}-?\d{4}$/;
phoneRegex.test("010-1234-5678"); // true
phoneRegex.test("01012345678"); // true
// URL
const urlRegex = /^https?:\/\/[\w.-]+(?:\/[\w./?%&=-]*)?$/;
urlRegex.test("https://example.com/path?q=1"); // true
// 한글만
const koreanRegex = /^[가-힣]+$/;
koreanRegex.test("안녕하세요"); // true
koreanRegex.test("Hello"); // false
// 비밀번호 (영문+숫자+특수문자, 8자 이상)
const passwordRegex = /^(?=.*[a-zA-Z])(?=.*\d)(?=.*[!@#$%^&*]).{8,}$/;
passwordRegex.test("Abc123!@"); // true
replace와 정규식
// 캡처 그룹 참조 ($1, $2)
"2026-03-28".replace(/(\d{4})-(\d{2})-(\d{2})/, "$1년 $2월 $3일");
// "2026년 03월 28일"
// 전화번호 포맷팅
"01012345678".replace(/(\d{3})(\d{4})(\d{4})/, "$1-$2-$3");
// "010-1234-5678"
// HTML 태그 제거
"<p>안녕</p>".replace(/<[^>]*>/g, "");
// "안녕"
matchAll — 모든 매칭과 그룹
const text = "가격: 1000원, 할인: 200원, 합계: 800원";
const regex = /(\d+)원/g;
for (const match of text.matchAll(regex)) {
console.log(`전체: ${match[0]}, 숫자: ${match[1]}, 위치: ${match.index}`);
}
// 전체: 1000원, 숫자: 1000, 위치: 4
// 전체: 200원, 숫자: 200, 위치: 14
// 전체: 800원, 숫자: 800, 위치: 24
**기억하기 **:
\d는 숫자,\w는 단어,\s는 공백입니다. 대문자는 각각의 반대입니다.^는 시작,$는 끝을 의미합니다. 이 기본만 알면 대부분의 실전 패턴을 읽고 작성할 수 있습니다.
댓글 로딩 중...