DevToolBox무료
블로그

Regex 치트 시트: 정규표현식 완전 참조 가이드

12분 읽기by DevToolBox

정규 표현식(regex)은 개발자 도구 중 가장 강력한 도구 중 하나입니다. 사용자 입력 검증, 로그 파일 파싱, 복잡한 검색-치환 작업 등 regex는 비할 데 없는 정밀도를 제공합니다. 이 정규식 완전 치트시트는 앵커, 문자 클래스, 수량자, 그룹, 전후방 탐색, 플래그 등 모든 주요 개념을 다룹니다.

Regex 테스터에서 모든 패턴을 실시간으로 테스트하세요 ->

기본 문법: 앵커와 문자 클래스

앵커와 문자 클래스는 모든 regex 패턴의 기초입니다. 앵커는 매칭이 어디서 발생하는지를, 문자 클래스는 어떤 문자를 매칭할지 정의합니다.

앵커

앵커는 문자가 아닌 문자열 내의 위치에 매칭됩니다.

PatternDescriptionExample
^Start of string (or line with m flag)^Hello matches "Hello World"
$End of string (or line with m flag)world$ matches "Hello world"
\bWord boundary\bcat\b matches "cat" but not "catch"
\BNon-word boundary\Bcat\B matches "concatenate"
\AAbsolute start of string (Python, Ruby)\AHello
\ZAbsolute end of string (Python, Ruby)bye\Z

문자 클래스

문자 클래스는 단일 위치에서 문자 집합을 매칭합니다.

PatternDescriptionEquivalent
[abc]Match a, b, or c--
[^abc]Match anything except a, b, c--
[a-z]Match any lowercase letter--
[A-Z]Match any uppercase letter--
[0-9]Match any digit\d
.Match any character (except newline by default)--
\dDigit[0-9]
\DNon-digit[^0-9]
\wWord character[a-zA-Z0-9_]
\WNon-word character[^a-zA-Z0-9_]
\sWhitespace (space, tab, newline)[ \t\n\r\f\v]
\SNon-whitespace[^ \t\n\r\f\v]

특수 문자 (메타문자)

이 문자들은 regex에서 특별한 의미를 가집니다. 리터럴 매칭을 위해 백슬래시로 이스케이프하세요.

Special characters that need escaping:
.  ^  $  *  +  ?  {  }  [  ]  \  |  (  )

To match a literal dot:   \.
To match a literal star:  \*
To match a literal pipe:  \|
To match a backslash:     \\

수량자: 매칭 횟수

수량자는 반복 횟수를 제어합니다. 기본적으로 탐욕적이며, ?를 추가하면 게으른 모드가 됩니다.

GreedyLazyDescription
**?0 or more times
++?1 or more times
???0 or 1 time (optional)
{n}{n}?Exactly n times
{n,}{n,}?n or more times
{n,m}{n,m}?Between n and m times

탐욕적 vs. 게으른

탐욕적 <.*>는 전체 문자열과 매칭되고, <.*?>는 첫 번째 태그만 매칭합니다.

// Input string:
const str = '<b>bold</b> and <i>italic</i>';

// Greedy: matches from first < to LAST >
str.match(/<.*>/);
// Result: '<b>bold</b> and <i>italic</i>'

// Lazy: matches from first < to FIRST >
str.match(/<.*?>/);
// Result: '<b>'

그룹과 캡처

그룹은 여러 문자를 하나의 단위로 취급하고 매칭된 부분을 추출할 수 있습니다.

캡처 그룹

(...)로 매칭을 캡처합니다. \1, \2 등으로 역참조합니다.

// Capturing group example
const dateRegex = /^(\d{4})-(\d{2})-(\d{2})$/;
const match = '2026-02-10'.match(dateRegex);
// match[0] = '2026-02-10'  (full match)
// match[1] = '2026'        (year)
// match[2] = '02'          (month)
// match[3] = '10'          (day)

// Backreference: match repeated words
const repeated = /\b(\w+)\s+\1\b/;
repeated.test('the the');  // true
repeated.test('the cat');  // false

명명된 그룹

(?<name>...)으로 가독성을 향상시킵니다.

// Named groups in JavaScript
const dateRegex = /^(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})$/;
const match = '2026-02-10'.match(dateRegex);
// match.groups.year  = '2026'
// match.groups.month = '02'
// match.groups.day   = '10'
# Named groups in Python
import re
pattern = r'^(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})$'
m = re.match(pattern, '2026-02-10')
# m.group('year')  = '2026'
# m.group('month') = '02'
# m.group('day')   = '10'

비캡처 그룹

캡처가 필요 없을 때 (?:...)를 사용합니다.

// Non-capturing group
const regex = /(?:https?|ftp):\/\/[^\s]+/;
// Groups the protocol options without capturing them
// Only the full URL is in match[0]

대안 (OR)

파이프 |로 여러 대안 중 하나를 매칭합니다.

// Alternation examples
/cat|dog/           // Match "cat" or "dog"
/(red|blue) car/    // Match "red car" or "blue car"
/^(GET|POST|PUT|DELETE)\s/  // Match HTTP methods

전방탐색과 후방탐색 (제로 너비 어서션)

전후방 탐색은 현재 위치 앞뒤에 패턴이 존재하는지를 문자를 소비하지 않고 확인합니다.

SyntaxTypeDescription
(?=...)Positive lookaheadWhat follows must match
(?!...)Negative lookaheadWhat follows must NOT match
(?<=...)Positive lookbehindWhat precedes must match
(?<!...)Negative lookbehindWhat precedes must NOT match

긍정 전방탐색 (?=...)

지정 패턴이 뒤따르는 위치에 매칭.

// Match a number followed by "px"
/\d+(?=px)/
// "20px 30em 40px" → matches "20" and "40" (not "30")

// Password: must contain at least one digit
/^(?=.*\d).{8,}$/

부정 전방탐색 (?!...)

지정 패턴이 뒤따르지 않는 위치에 매칭.

// Match "cat" NOT followed by "fish"
/cat(?!fish)/
// "catfish catdog" → matches "cat" in "catdog" only

// Match numbers NOT followed by a unit
/\d+(?!\s*(px|em|rem|%))/

긍정 후방탐색 (?<=...)

지정 패턴이 앞에 있는 위치에 매칭.

// Match a number preceded by "$"
/(?<=\$)\d+(\.\d{2})?/
// "$49.99 and €29.99" → matches "49.99" only

// Extract value after "price:"
/(?<=price:\s*)\d+/

부정 후방탐색 (?<!...)

지정 패턴이 앞에 없는 위치에 매칭.

// Match "cat" NOT preceded by "wild"
/(?<!wild)cat/
// "wildcat housecat" → matches "cat" in "housecat" only

// Match digits not preceded by a minus sign
/(?<!-)\b\d+\b/

참고: 후방탐색은 일부 엔진에서 제한적입니다. Go의 RE2 엔진은 전후방 탐색을 지원하지 않습니다.

Regex 플래그 (수정자)

플래그는 regex 엔진의 패턴 해석 방식을 변경합니다.

FlagNameDescriptionExample
gGlobalFind all matches, not just the first/cat/g finds all "cat" occurrences
iCase-insensitiveMatch upper and lowercase interchangeably/hello/i matches "Hello", "HELLO"
mMultiline^ and $ match line starts/ends/^start/m matches at each line start
sDotall (Single-line). matches newline characters too/a.b/s matches "a\nb"
uUnicodeEnable full Unicode matching/\u{1F600}/u matches emoji
yStickyMatch only at lastIndex positionUsed for tokenizing / lexing
// Combining flags
const regex = /^hello world$/gim;

// In Python, flags are constants:
import re
pattern = re.compile(r'^hello world$', re.IGNORECASE | re.MULTILINE)

// In Go, use inline flags:
// (?i) for case-insensitive, (?m) for multiline, (?s) for dotall
regexp.MustCompile("(?im)^hello world$")

자주 쓰는 패턴 빠른 참조

가장 자주 필요한 regex 패턴 모음입니다.

Use CasePattern
Email^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$
URL (HTTP/S)^https?:\/\/[^\s]+$
IPv4 Address^((25[0-5]|(2[0-4]|1\d|[1-9]|)\d)\.?\b){4}$
Date (YYYY-MM-DD)^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$
Time (HH:MM:SS)^([01]\d|2[0-3]):[0-5]\d:[0-5]\d$
Hex Color^#([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$
Strong Password^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&]).{8,}$
Phone (E.164)^\+[1-9]\d{1,14}$
UUID^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$
Semantic Version^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(-[\w.]+)?(\+[\w.]+)?$
HTML Tag<([a-zA-Z][a-zA-Z0-9]*)\b[^>]*>(.*?)<\/\1>
Trim Whitespace^\s+|\s+$

Regex 테스터에서 모든 패턴 테스트하기 ->

프로그래밍 언어별 Regex

문법은 대부분 공통이지만 각 언어마다 고유한 API가 있습니다.

JavaScript

// Creating regex in JavaScript
const regex1 = /^\d+$/;             // Literal syntax
const regex2 = new RegExp('^\\d+$'); // Constructor (needs double-escape)

// Testing
regex1.test('12345');                // true

// Matching
'hello world'.match(/\w+/g);        // ['hello', 'world']

// Replacing
'2026-02-10'.replace(
  /^(\d{4})-(\d{2})-(\d{2})$/,
  '$2/$3/$1'
);  // '02/10/2026'

// matchAll (ES2020) - get all matches with groups
const text = 'Price: $10, Tax: $2';
for (const m of text.matchAll(/\$(\d+)/g)) {
  console.log(m[0], m[1]);
  // '$10' '10', then '$2' '2'
}

// Named groups (ES2018+)
const { groups } = '2026-02-10'.match(
  /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/
);
console.log(groups.year);  // '2026'

Python

import re

# Compile for reuse (recommended)
pattern = re.compile(r'^\d+$')

# Test if the entire string matches
pattern.match('12345')      # Match object (truthy)
pattern.match('abc')        # None (falsy)

# Search anywhere in the string
re.search(r'\d+', 'abc 123 def')  # Finds '123'

# Find all matches
re.findall(r'\w+', 'hello world')  # ['hello', 'world']

# Replace
re.sub(
    r'^(\d{4})-(\d{2})-(\d{2})$',
    r'\2/\3/\1',
    '2026-02-10'
)  # '02/10/2026'

# Named groups
m = re.match(
    r'(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})',
    '2026-02-10'
)
m.group('year')   # '2026'
m.group('month')  # '02'

# Flags
re.findall(r'^start', text, re.MULTILINE | re.IGNORECASE)

# Split by pattern
re.split(r'[,;\s]+', 'a, b; c  d')  # ['a', 'b', 'c', 'd']

Go (Golang)

package main

import (
    "fmt"
    "regexp"
)

func main() {
    // Compile (panics on invalid pattern)
    re := regexp.MustCompile(`^\d+$`)

    // Test
    fmt.Println(re.MatchString("12345"))  // true
    fmt.Println(re.MatchString("abc"))    // false

    // Find first match
    re2 := regexp.MustCompile(`\d+`)
    fmt.Println(re2.FindString("abc 123 def"))  // "123"

    // Find all matches
    fmt.Println(re2.FindAllString("10 cats and 20 dogs", -1))
    // ["10", "20"]

    // Replace
    re3 := regexp.MustCompile(`(\d{4})-(\d{2})-(\d{2})`)
    result := re3.ReplaceAllString("2026-02-10", "$2/$3/$1")
    fmt.Println(result)  // "02/10/2026"

    // Named groups
    re4 := regexp.MustCompile(`(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})`)
    match := re4.FindStringSubmatch("2026-02-10")
    for i, name := range re4.SubexpNames() {
        if name != "" {
            fmt.Printf("%s: %s\n", name, match[i])
        }
    }
    // year: 2026, month: 02, day: 10

    // Inline flags: (?i) case-insensitive, (?m) multiline, (?s) dotall
    re5 := regexp.MustCompile(`(?i)hello`)
    fmt.Println(re5.MatchString("HELLO"))  // true
}

Go는 RE2 엔진을 사용하며 전방탐색, 후방탐색, 역참조를 지원하지 않습니다.

성능 팁과 모범 사례

구체적으로: . 대신 [a-zA-Z]를 사용하세요.

치명적 백트래킹 방지: (a+)+ 같은 중첩 수량자를 피하세요.

// BAD: Catastrophic backtracking risk
const bad = /^(a+)+$/;
bad.test('aaaaaaaaaaaaaaaaaaaaa!');  // Extremely slow!

// GOOD: Flatten nested quantifiers
const good = /^a+$/;
good.test('aaaaaaaaaaaaaaaaaaaaa!'); // Instant: false

비캡처 그룹 사용: 캡처가 불필요하면 (?:...)를 사용하세요.

한 번 컴파일: Python과 Go에서는 컴파일된 regex 객체를 재사용하세요.

# Python: compile once, reuse many times
import re
email_re = re.compile(r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$')

# Fast: uses pre-compiled pattern
for addr in addresses:
    if email_re.match(addr):
        print(f"Valid: {addr}")

점진적 테스트: 복잡한 패턴은 단계별로 구축하세요.

Regex 테스터에서 모든 패턴을 실시간으로 테스트하세요 ->

자주 묻는 질문

정규식 치트시트란 무엇이고 왜 필요한가요?

문법, 메타문자, 수량자, 플래그, 일반 패턴을 한 곳에 모은 빠른 참조 가이드입니다. 숙련된 개발자도 모든 것을 외울 수 없습니다.

regex에서 .*와 .*?의 차이는 무엇인가요?

.*는 탐욕적(가장 긴 매칭), .*?는 게으른(가장 짧은 매칭). 첫 번째 구분자에서 멈추려면 게으른 수량자를 사용하세요.

모든 프로그래밍 언어가 같은 regex 문법을 지원하나요?

대부분 PCRE를 지원하지만 고급 기능은 다릅니다. JavaScript는 ES2018에서 후방탐색 추가, Go(RE2)는 지원하지 않습니다.

regex 패턴을 어떻게 테스트하고 디버그하나요?

실시간 매칭을 보여주는 인터랙티브 Regex 테스터를 사용하세요. 패턴을 단계별로 구축하세요.

치명적 백트래킹이란 무엇인가요?

regex 엔진이 문자열 불일치를 판단하는 데 기하급수적 시간이 걸리는 현상입니다. 중첩 수량자를 피하고 문자 클래스를 구체적으로 지정하세요.

𝕏 Twitterin LinkedIn
도움이 되었나요?

최신 소식 받기

주간 개발 팁과 새 도구 알림을 받으세요.

스팸 없음. 언제든 구독 해지 가능.

Try These Related Tools

.*Regex TesterR✓Regex CheckerR≈Regex MatcherR+Regex Generator

Related Articles

개발자가 필요한 20가지 Regex 패턴: 복사 가능한 예시

이메일, URL, 전화, 비밀번호, IP 주소 등 20가지 검증된 정규식 패턴 모음.

이메일, 전화번호, URL, IP 검증용 정규식 패턴 (복사-붙여넣기 가능)

이메일, 전화번호, URL, IP 주소를 검증하는 복사-붙여넣기 가능한 정규식 패턴. JavaScript, Python 등 지원.

온라인 정규식 테스터: 정규 표현식 실시간 테스트, 디버그 & 검증 (2026 가이드)

무료 온라인 정규식 테스터로 실시간 정규 표현식 테스트. JavaScript, Python, Go 정규식 문법, 필수 패턴 10가지, 흔한 실수, 성능 팁 포함.