Skip to content

정규식 치트시트

패턴 매칭과 텍스트 처리를 위한 정규식.

01

시작하기

기본 문법

정규식은 패턴 매칭에 특수 문자를 사용합니다. .는 모든 문자와 일치하고, []는 문자 클래스를 정의하며, \d \w \s는 자주 쓰는 집합의 축약형입니다. [] 안에서 ^는 부정을 뜻합니다.

regex
# Basic matching
hello       # literal match
.           # any character except newline
[abc]       # any of a, b, c
[^abc]      # not a, b, or c
[a-z]       # range a to z
\d          # digit [0-9]
\D          # non-digit
\w          # word char [a-zA-Z0-9_]
\W          # non-word char
\s          # whitespace
\S          # non-whitespace

메타 문자

메타 문자는 특별한 의미를 가집니다. 문자 그대로 일치시키려면 백슬래시를 붙이세요. 문자 클래스 [] 안에서는 ] \ ^ -만 이스케이프가 필요합니다(그리고 -는 시작/끝에 있지 않을 때만).

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

# Escape with backslash to match literally
\.           # literal dot
\*           # literal asterisk
\+           # literal plus
\?           # literal question mark
\(           # literal parenthesis
\[           # literal bracket
\$           # literal dollar
\^           # literal caret
\\           # literal backslash

# Example: match "1.5" not "1x5"
1\.5         # matches "1.5" only

점과 와일드카드

점 .은 가장 흔한 와일드카드지만 기본적으로 줄바꿈과 일치하지 않습니다. 여러 줄에 걸쳐 일치시켜야 한다면 /s 플래그(ES2018+)를 쓰거나, 엔진 간 호환성을 위해 [\s\S] 같은 문자 클래스 기법을 사용하세요.

regex
# Dot matches any char except newline (by default)
a.c          # matches "abc", "a c", "a1c", "a@c"
a..c         # four chars: a, any, any, c

# Dot matches newline only with /s flag (dotall)
/a.b/s       # "a\nb" matches

# Match any character truly (with /s flag)
/[\s\S]/     # any char including newline (portable)
/[\d\D]/     # also any char
/[\w\W]/     # also any char

# Practical: any chars between tags
<div[\s\S]*?</div>

코드에서 정규식 리터럴

JS에서는 /pattern/flags가 가장 흔합니다. Python에서는 이중 이스케이프를 피하려고 원시 문자열(r"")을 사용하세요. Java의 문자열 리터럴에는 백슬래시를 두 번 써야 합니다. PHP는 /를 구분자로 사용합니다. Go는 백틱이나 "\\\\" 문자열을 사용합니다.

regex
# JavaScript - regex literal
const re = /\bword\b/gi;

# JavaScript - constructor (for dynamic patterns)
const re2 = new RegExp("\\bword\\b", "gi");

# Python - raw string with re module
import re
pattern = r"\bword\b"
re.search(pattern, "a word here")

# Java - String needs double escaping
Pattern p = Pattern.compile("\\bword\\b");

# PHP - Perl-style
if (preg_match('/\\bword\\b/i', $text)) { }

# Go - RE2 syntax
re := regexp.MustCompile(`\\bword\\b`)

테스트와 매칭

JS의 test()는 불리언을, match()는 매치를 반환합니다. Python의 search()는 어디서든 찾고, match()는 시작에 고정되며, fullmatch()는 전체 문자열이 일치해야 합니다. 의도에 맞는 함수를 선택하세요.

regex
# JavaScript
/abc/.test("abcdef")        # true
"abcdef".match(/abc/)       # ["abc", index: 0]
"abcabc".match(/abc/g)      # ["abc", "abc"]
"abcdef".search(/abc/)      # 0 (index)

# Python
import re
re.search(r"abc", "abcdef")  # Match object or None
re.match(r"abc", "abcdef")   # anchored at start
re.fullmatch(r"abc", "abc")  # entire string

# Test if pattern matches anywhere
bool(re.search(r"abc", "xabcx"))  # True
02

문자 클래스

문자 집합 [abc]

대괄호는 나열된 문자 중 하나와 일치하는 문자 집합을 정의합니다. [] 안에서는 대부분의 메타 문자(. * + ? 등)가 특별한 의미를 잃고 문자 그대로 일치합니다. ] \ ^ -만 특별합니다.

regex
# Match any single char from the set
[aeiou]      # any vowel
[abc123]     # any of a, b, c, 1, 2, 3
[ABC]        # uppercase A, B, or C (case-sensitive)

# In a set, most metacharacters are literal
[.*+]        # literal . * or +
[()]         # literal ( or )

# Quantifiers work on sets
[aeiou]{2}   # exactly two vowels
[0-9]+       # one or more digits

부정 집합 [^abc]

여는 [ 바로 뒤에 ^를 두면 집합이 부정되어 나열되지 않은 모든 문자와 일치합니다. ^가 첫 번째여야 하며, 그 밖의 위치에서는 문자 그대로의 캐럿입니다. 'X까지' 같은 패턴에 유용합니다.

regex
# Caret at start negates the set
[^aeiou]     # any char that is NOT a vowel
[^0-9]       # any non-digit
[^\s]        # any non-whitespace
[^a-zA-Z]    # any non-letter

# Common: match up to a delimiter
[^,]+        # everything until next comma
[^;]+        # everything until next semicolon
[^"\\]      # any char except quote or backslash

# Negation works with quantifiers
[^aeiou]+    # one or more non-vowels

범위 [a-z]

두 문자 사이의 하이픈은 문자 코드에 기반한 범위를 만듭니다. 범위는 낮은 값에서 높은 값으로 가야 합니다. 집합 안에서 하이픈 자체를 일치시키려면 시작/끝에 두거나 이스케이프하세요. Z와 a 사이의 비문자 문자를 포함하는 [A-z]는 피하세요.

regex
# Hyphen defines a range inside []
[a-z]        # lowercase letter
[A-Z]        # uppercase letter
[0-9]        # digit (same as \d)
[a-zA-Z]     # any letter
[a-zA-Z0-9]  # alphanumeric
[a-fA-F0-9]  # hexadecimal digit

# ASCII order matters
[A-z]        # WARNING: includes [ \ ] ^ _ `

# Multiple ranges in one set
[a-zA-Z0-9_]  # word character (same as \w)

# Literal hyphen: place at start or end, or escape
[-a-z]       # hyphen or lowercase letter
[a-z-]       # lowercase letter or hyphen
[a\-z]       # a, hyphen, or z

미리 정의된 축약형

축약형 \d \w \s는 간결하고 읽기 쉽습니다. 유니코드 모드(Python 3 기본, JS는 /u 사용)에서는 \d와 \w가 ASCII보다 넓게 일치합니다. ASCII만 원하면 Python에서 re.ASCII를 쓰거나 [0-9]를 명시하세요.

regex
# Most common shorthands (work outside and inside [])
\d    # digit [0-9]
\w    # word char [a-zA-Z0-9_]
\s    # whitespace [ \t\n\r\f\v]
\D    # non-digit
\W    # non-word char
\S    # non-whitespace

# With ASCII-only flag (Python)
\d      # Unicode digits by default
\d      # [0-9] with re.ASCII flag

# Inside character classes
[\d\s]    # digit or whitespace
[\w.]     # word char or literal dot
[a-z\d]   # letter or digit

# POSIX classes (PCRE, not JS)
[[:alpha:]]  # letters
[[:digit:]]  # digits
[[:alnum:]]  # alphanumeric
[[:space:]]  # whitespace

부정 축약형

대문자 버전 \D \W \S는 소문자 버전을 부정합니다. 줄바꿈과 다른 문자도 포함합니다. '숫자가 아니면서 줄바꿈도 아닌' 문자를 원하면 [^\d\n]처럼 명시적으로 조합하세요.

regex
# Uppercase versions are negations
\D    # any non-digit            [^0-9]
\W    # any non-word char        [^a-zA-Z0-9_]
\S    # any non-whitespace       [^\s]

# Useful for "match until X" patterns
\S+        # one or more non-whitespace (a word)
\D+        # one or more non-digits
\W         # a single non-word char

# Combined with anchors
^\S+       # word at start of string
\S+$       # word at end of string

# Find non-word boundaries for tokenization
\W+        # split on punctuation/space

# Caveat: \D matches newlines too
[^\d\n]    # non-digit AND non-newline

클래스 조합

문자 클래스는 범위, 축약형, 리터럴을 섞을 수 있습니다. 순서는 중요하지 않습니다(범위와 맨 앞의 ^는 예외). 이들을 조합해 이메일, 파일 이름, 식별자 같은 실용적인 패턴을 만드세요.

regex
# Mix shorthands, ranges, and literals in []
[\w\s]       # word char or whitespace
[a-z\d_]     # lowercase, digit, or underscore
[\w.-]       # word char, dot, or hyphen (e.g., domain)
[^\w\s]     # neither word char nor whitespace (punctuation)

# Common practical classes
[A-Z][a-z]+       # Capitalized word
\d{1,3}\.\d{1,3}  # version-like number
[\w.+-]+@\w+     # email-ish

# Hex color
#[a-fA-F0-9]{3,6}

# Match identifier (variable name)
[a-zA-Z_$][\w$]*

# Filename with extension
[\w.-]+\.[a-zA-Z]{1,5}
03

수량자

별표 *(0개 이상)

*는 앞 요소가 0개 이상 일치합니다. 기본적으로 탐욕적이라 최대한 많이 일치합니다. ?를 붙이면 최소 일치(*?)가 됩니다. https?:// 같은 '선택적' 패턴에 ?와 함께 자주 쓰입니다.

regex
# * matches 0 or more occurrences
ab*c        # "ac", "abc", "abbc", "abbbbc"
\d*         # zero or more digits
\s*         # optional whitespace
[a-z]*      # zero or more lowercase letters

# Useful for optional content
https?://   # http:// or https:// (note the ?)
color:\s*#?[a-f0-9]+   # color: #abc or color: abc

# * is greedy - matches as much as possible
<a.*>       # from <a to LAST > on the line

# Make it lazy with ?
<a.*?>      # from <a to FIRST > (lazy)
.*?         # zero or more, lazy

# * on group
(ab)*       # "", "ab", "abab", "ababab"

플러스 +(1개 이상)

+는 최소 하나 이상 일치해야 합니다(0개를 허용하는 *와 다름). 단어(\w+), 숫자(\d+), 공백 연속(\s+) 같은 '하나 이상' 패턴에 유용합니다. 최소 일치 버전 +?는 첫 매치에서 멈춥니다.

regex
# + matches 1 or more occurrences (at least one)
ab+c        # "abc", "abbc", but NOT "ac"
\d+         # one or more digits (integer)
\w+         # one or more word chars (a word)
\s+         # one or more whitespace

# Common patterns
\w+@\w+             # simplistic email
\d+\.\d+           # decimal number
-?\d+               # optional sign + integer
[A-Z]+              # one or more uppercase

# Greedy by default - use +? for lazy
".+?"        # quoted string (lazy: stops at first ")
".+"         # greedy: matches to the LAST "

# + vs *: + requires at least one
a+           # "a", "aa", "aaa" (not "")
a*           # "", "a", "aa", "aaa"

물음표 ?(0개 또는 1개)

?는 앞 요소를 선택적으로 만듭니다(0 또는 1). 다른 수량자 뒤에 붙으면(*? +? ??) 그 수량자를 최소 일치로 바꿉니다. 선택적 문자, 부호, 구분자, 'Nov'/'November' 같은 짧은/긴 형태에 유용합니다.

regex
# ? matches 0 or 1 occurrence (optional)
colou?r     # "color" or "colour"
https?://   # "http://" or "https://"
-?\d+       # integer with optional minus sign
[+-]?\d*    # number with optional sign

# Make greedy quantifier lazy
.*?          # lazy zero-or-more
.+?          # lazy one-or-more
??           # lazy zero-or-one (rarely needed)

# Optional group
Nov(?:ember)?  # "Nov" or "November"
Mr\.?         # "Mr" or "Mr."

# Optional non-capturing group with separator
\d{4}[-/]?(\d{2})  # 2024-01 or 202401

# Chained optionals
a?b?c?       # "", "a", "ab", "abc", "b", "bc", "c"

중괄호 {n,m}

중괄호는 정확한 개수를 지정합니다. {n}(정확히 n개), {n,m}(n에서 m개), {n,}(n개 이상), {0,m}(최대 m개). 대부분의 엔진은 유효한 수량자를 이루지 않는 {를 리터럴로 취급합니다. ?를 붙이지 않으면 항상 탐욕적입니다.

regex
# Exact count
\d{3}        # exactly 3 digits
[a-z]{5}     # exactly 5 lowercase letters
.{10}        # exactly 10 of any char

# Range: min, max
\d{2,4}      # 2 to 4 digits
\w{3,}       # 3 or more word chars
.{0,5}       # 0 to 5 of any char (same as.....?)

# Open-ended
\d{3,}       # 3 or more digits
\s{1,}       # one or more whitespace (same as \s+)
\d{0,}       # zero or more (same as \d*)

# Practical patterns
\d{4}-\d{2}-\d{2}        # date YYYY-MM-DD
\d{1,3}(?:\.\d{1,3}){3}  # IPv4 address
\d{3}-\d{3}-\d{4}        # US phone
[A-Fa-f0-9]{6}             # 6 hex digits
\d{4,16}                   # 4-16 digit PIN

# Greedy by default - add ? for lazy
\d{2,4}?    # match minimum (2)

탐욕적 수량자

탐욕적 수량자는 최대한 많이 소비한 뒤, 나머지 패턴이 일치하도록 역추적합니다. 이 때문에 HTML/텍스트에서 예상치 못한 매치가 생길 수 있습니다. 최소 일치(*? +?)를 쓰거나 문자 클래스로 더 구체적으로 지정해 문제를 피하세요.

regex
# Quantifiers are greedy by default
# They match as MUCH as possible while allowing rest to match
".*"          # in 'a "b" c "d" e', matches "b" c "d"
<a.*>         # matches from <a to the LAST >

# Greedy backtracks to allow overall match
\d+\d        # in "12345", \d+ takes "1234", last \d takes "5"

# Common greedy patterns
.*            # entire line
.+            # entire line (at least 1 char)
\d+           # all consecutive digits
\w+           # all consecutive word chars

# Greedy can be a problem with HTML
<.*>          # WRONG: matches <b>text</b> as one
<\w+>         # better: matches just <b>

# Greedy with anchored end
^.*(end).*$   # .* takes everything, backtracks to find "end"

최소 일치 수량자

최소 일치 수량자(비탐욕적, 소극적이라고도 함)는 필요한 만큼만 확장하며 최소한으로 일치합니다. 따옴표나 태그 사이 내용처럼 가장 짧은 매치를 찾을 때 사용하세요. 따옴표 문자열에는 '.*?'보다 '[^']*'가 더 명확하고 빠른 경우가 많습니다.

regex
# Add ? to make any quantifier lazy (match as LITTLE as possible)
*?    # lazy zero-or-more
+?    # lazy one-or-more
??    # lazy zero-or-one
{n,m}?  # lazy range

# Lazy matches shortest possible
"<.*?>"      # in 'a "b" c "d" e', matches "b" then "d"
<a.*?>       # matches <a> to first >

# Compare: HTML tag matching
<.+>         # greedy: <b>bold</b> matches as ONE
<.+?>        # lazy: matches <b> then </b> separately

# Find quoted strings (lazy)
"([^"]*)"    # alternative: chars that aren't a quote

# Lazy can be slower in some cases
# Prefer negated classes when possible:
"[^"]*"      # often faster than ".*?"

# Multiple lazy on same line
(.*?)(.*?)(.*?)   # all lazy, but each takes minimum
04

앵커와 경계

시작 앵커 ^

^는 문자열의 시작(/m 플래그가 있으면 각 줄의 시작)과 일치합니다. 너비가 0인 단언이라 문자를 소비하지 않습니다. [] 안의 ^(문자 클래스 부정)와 혼동하지 마세요. 전체 문자열을 검증하려면 ^...$를 사용하세요.

regex
# ^ matches position at start of string (or line with /m)
^Hello        # "Hello" only at the start
^\d+          # digits at the start
^https?://    # URL at start of string

# With multiline flag /m, ^ matches start of each line
^\s*$         # blank lines (with /m, matches each)

# Useful for validation (must start with)
^[A-Z]        # must start with uppercase letter
^[a-zA-Z]     # must start with a letter

# ^ inside [] is DIFFERENT (negation)
[^abc]        # any char that is NOT a, b, or c

# Common validation: entire string is digits
^\d+$         # only digits, nothing else

# Line prefix matching (multiline)
^\s*#.*       # comment lines starting with #

끝 앵커 $

$는 문자열의 끝(/m이 있으면 줄의 끝)과 일치합니다. ^...$를 결합해 전체 문자열이 패턴과 일치하는지 검증하세요. 선택(alternation)에 주의하세요. ^a|b$는 (^a) 또는 (b$)를 뜻하므로 ^(a|b)$나 ^(?:a|b)$를 사용하세요.

regex
# $ matches position at end of string (or before final newline)
end$          # "end" only at the end
\.\w{2,4}$    # file extension at end
\d+$          # digits at the end

# With multiline flag /m, $ matches end of each line
\s*$          # trailing whitespace per line (with /m)

# Combine ^ and $ for full-string validation
^\d{4}$        # exactly 4 digits, nothing else
^[A-Z][a-z]+$  # Capitalized word, entire string
^yes|no$       # WARNING: this is (^yes) OR (no$)

# Fix the precedence issue:
^(?:yes|no)$   # entire string is "yes" or "no"

# Email-ish validation
^[\w.+-]+@[\w-]+\.[a-z]{2,}$

# Multiline: find empty lines
^$             # empty lines (with /m)

단어 경계 \b

\b는 \w(단어 문자)와 \W(비단어 문자) 또는 문자열 끝 사이의 경계와 일치하는 너비 0 단언입니다. 부분 문자열이 아닌 단어 전체를 일치시킬 때 완벽합니다. 밑줄은 단어 문자이므로 'foo_bar'는 \b에게 하나의 단어입니다.

regex
# \b matches a position between a word char and non-word char
\bword\b      # "word" but not "wording" or "sword"
\bcat         # "cat" at start of word: cat, cats, but not scat
cat\b         # "cat" at end of word: cat, scat, but not cats
\bcat\b       # "cat" as a whole word only

# Useful for finding whole words
\bthe\b       # "the" but not "theater" or "breathe"

# Find words of specific length
\b\w{4}\b      # all 4-letter words
\b\w{4,}\b    # all words with 4+ letters

# Boundary at start/end of identifier
\bUser\b      # whole word "User"
\bid\b         # whole word "id" (not "id" in "ride")

# Variable name as whole word
\bcount\b     # "count" but not "discount" or "counter"

# Boundary between digit and non-digit
\b\d+\b       # whole numbers only

비단어 경계 \B

\B는 단어 경계가 아닌 모든 위치와 일치합니다. 패턴이 단어의 시작/끝이 아님을 보장할 때 유용합니다. 드물지만 다른 단어 안의 'cat' 같은 특정 사례에 강력합니다.

regex
# \B is the opposite of \b - matches where there is NO word boundary
\Bword        # "word" NOT at start of word: "sword", "password"
word\B        # "word" NOT at end of word: "wording", "wordsword"
\Bword\B      # "word" in middle of other word chars

# Find 'cat' inside another word only
\Bcat\B       # matches in " concatenate " (middle 'cat')

# Useful for matching inside identifiers
\Ba\B         # 'a' surrounded by word chars

# Position NOT at word boundary
\B-\B         # hyphen between word chars (e.g., "well-known")

# Practical: hyphenated compound word
\w+\B-\B\w+   # NOT what you want for "well-known"

# \B at start of string with first char being non-word
\B.           # any char that's NOT at a word boundary start

# Test password: 'a' must be inside word (rare)
\Ba\w+\B      # 'a' not at word edges

문자열 앵커 \A \Z \z

\A와 \z/\Z는 여러 줄 모드의 영향을 받지 않는 절대 문자열 앵커입니다(Python, PCRE, Ruby, Java). \A는 시작, \z는 끝, \Z는 끝 또는 마지막 줄바꿈 앞입니다. JS에는 없으므로 ^와 $(줄 모드는 /m)를 사용하세요. Ruby의 ^ $는 항상 줄 기반입니다.

regex
# These anchors are NOT in JavaScript natively (use ^ and $)
# Available in Python, Java, PCRE, Ruby, etc.

\A            # absolute start of string (not affected by /m)
\Z            # end of string, or before final newline (Python/PCRE)
\z            # absolute end of string (no newline tolerance)

# Python example
import re
re.search(r"\Ahello", "hello\nworld")  # Match at start
re.search(r"world\Z", "hello\nworld\n")  # Match (before final \n)
re.search(r"world\z", "hello\nworld\n")  # No match (newline at end)

# Difference between ^ and \A with re.MULTILINE
text = "line1\nline2"
re.findall(r"^\w+", text, re.M)  # ['line1', 'line2']
re.findall(r"\A\w+", text, re.M)  # ['line1'] only

# JavaScript: only ^ and $ available
# Use ^ with /m for line starts
# Use $ with /m for line ends

# Ruby always treats ^ and $ as line anchors
# Use \A and \z for string anchors in Ruby
05

그룹과 캡처

캡처 그룹 ()

괄호 ()는 일치한 텍스트를 나중에 쓰도록 기록하는 캡처 그룹을 만듭니다. 그룹은 왼쪽에서 오른쪽으로 1부터 번호가 붙습니다. 매치의 일부를 추출하거나 교체 문자열/역참조에서 다시 참조할 때 사용하세요.

regex
# Parentheses create a capturing group
(abc)        # matches "abc" and captures it
(\d+)        # matches digits and captures them
(a)(b)(c)    # three separate capture groups

# Group with quantifier
(ab)+        # "ab", "abab", "ababab" (whole group repeated)
(\d{2,4})-   # 2-4 digits followed by hyphen

# Capturing in replacement (JS)
"2024-01-15".replace(/(\d{4})-(\d{2})-(\d{2})/, "$3/$2/$1")
# Result: "15/01/2024"

# Capturing in Python
import re
m = re.search(r"(\w+)@(\w+)", "[email protected]")
m.group(1)  # "user"
m.group(2)  # "example"
m.groups()  # ("user", "example")

# Backreference in same regex
(\w+)\s+\1   # repeated word: "hello hello"

그룹 번호

그룹은 여는 괄호의 위치에 따라 왼쪽에서 오른쪽으로 번호가 붙습니다. 바깥/중첩 그룹이 안쪽 그룹보다 앞입니다. 교체 문법은 언어마다 다릅니다. JS/Java는 $1, Python은 \1(또는 \g<1>), PHP는 $1과 \1을 모두 허용합니다.

regex
# Groups are numbered left-to-right by opening paren
(A)(B)(C)        # group 1=A, 2=B, 3=C
((A)(B))(C)      # group 1=AB, 2=A, 3=B, 4=C

# Nested groups: outer first, then inner
(\d{4})-(\d{2})-(\d{2})    # 1=year, 2=month, 3=day
((\d{1,3})\.){3}(\d{1,3})  # 1=last octet., 2=octet, 4=last octet

# Reference groups in replacement
# JavaScript: $1, $2, $3
"abc".replace(/(a)(b)(c)/, "$3$2$1")  # "cba"

# Python: \1, \2 in re.sub; m.group(1)
re.sub(r"(\w+)@(\w+)", r"\2.\1", "user@host")  # "host.user"

# Java: $1, $2 in replaceAll
"x".replaceAll("(x)", "$1$1")  # "xx"

# PHP: $1 or \1 in preg_replace
preg_replace('/(\w+)@(\w+)/', '$2.$1', 'user@host')

# Whole match: $& (JS), \g<0> (Python), $0 (Java/PHP)

비캡처 (?:...)

캡처가 필요 없을 때는 (?:...)로 그룹화하세요. 메모리를 절약하고 캡처 그룹 번호를 예측 가능하게 유지하며 의도를 드러냅니다. 캡처 값이 중요하지 않은 하위 패턴에 선택이나 수량자를 적용할 때 특히 중요합니다.

regex
# (?:...) groups WITHOUT capturing (saves memory, cleaner groups)
(?:abc)+         # "abc" repeated, but no capture
(?:\d{1,3}\.){3}\d{1,3}  # IPv4, no extra captures

# Compare: capturing vs non-capturing
(\d{4})-(\d{2})    # 2 groups captured
(?:\d{4})-(?:\d{2}) # 0 groups captured (just match)

# Use non-capturing when you don't need the captured value
https?://(?:www\.)?(\w+)  # capture just the domain
(?:Mr|Mrs|Ms)\.\s+\w+     # title prefix, no capture needed

# Combine with alternation
(?:cat|dog|bird)s?   # plural animals, no capture

# With quantifier on alternation
(?:\d+\s*)+         # numbers separated by spaces

# Why use it?
# 1. Saves memory (no captured text stored)
# 2. Keeps group numbering clean
# 3. Documents intent: "this is just for grouping"

명명 그룹 (?<name>...)

명명 그룹 (?<name>...) [JS/.NET] 또는 (?P<name>...) [Python/PCRE]는 패턴을 자기 문서화하게 만듭니다. 교체에서 이름으로 참조하고(JS는 $<name>, Python은 \g<name>), 역참조(JS는 \k<name>, Python은 (?P=name))로도 사용합니다.

regex
# Named capture group - JavaScript, .NET, Python 3.x style
(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})

# Python uses (?P<name>...) - same as PCRE
(?P<year>\d{4})-(?P<month>\d{2})

# Reference in replacement
# JavaScript:
"2024-01-15".replace(
  /(?<y>\d{4})-(?<m>\d{2})-(?<d>\d{2})/,
  "$<d>/$<m>/$<y>"
)  # "15/01/2024"

# Python:
re.sub(
  r"(?P<y>\d{4})-(?P<m>\d{2})-(?P<d>\d{2})",
  r"\g<d>/\g<m>/\g<y>",
  "2024-01-15"
)  # "15/01/2024"

# Reference by name in same regex (backreference)
(?<word>\w+)\s+\k<word>     # JS
(?P<word>\w+)\s+(?P=word)    # Python

# Access named groups in Python
m = re.match(r"(?P<year>\d{4})", "2024")
m.group("year")  # "2024"
m.groupdict()    # {"year": "2024"}

선택 |

선택 |은 여러 패턴 중 하나와 일치합니다. 우선순위가 매우 낮으므로 괄호로 범위를 지정하세요. 엔진은 왼쪽에서 오른쪽으로 시도하며 전체 매치가 성공하는 첫 번째를 선택합니다. 선택지가 겹치면 순서가 중요합니다.

regex
# | means OR - matches one of several alternatives
cat|dog|bird     # "cat" OR "dog" OR "bird"
yes|no           # "yes" or "no"
\d{2}|\d{4}     # 2 digits OR 4 digits

# IMPORTANT: alternation has low precedence
^abc|def$        # means (^abc) OR (def$) — NOT ^abc$ or ^def$

# Use groups to scope alternation
^(abc|def)$      # entire string is "abc" or "def"
^(?:cat|dog)s?$  # "cat", "cats", "dog", "dogs"

# Order matters - first match wins
a|ab             # in "ab", matches just "a" (leftmost wins)
ab|a             # in "ab", matches "ab"

# Common: file extensions
\.(?:jpg|png|gif|bmp)$

# HTML tags
</?(?:div|span|p|a)\b

# Day names
(?:Mon|Tues?|Wed|Thurs?|Fri|Sat|Sun)day

# Number formats
\d{1,3}(?:,\d{3})*|\d+   # 1,234 or 1234

그룹 역참조

역참조(\1, \2 또는 \k<name>)는 앞선 그룹이 캡처한 것과 같은 텍스트와 일치합니다. 고전적 용도: HTML/XML 태그 쌍 일치, 반복 단어 찾기, 일관된 구분자 보장. 역참조는 그룹이 캡처한 내용과 정확히 일치해야 합니다.

regex
# \1, \2, etc. refer to a previous capturing group's match
(\w+)\s+\1        # repeated word: "hello hello"
<(\w+)>.*?</\1>    # HTML tag matching: <div>...</div>
(["\'])[^\1]*\1   # quoted string (quote char remembered)

# Named backreferences
# JavaScript: \k<name>
(?<q>["\'])[^\k<q>]*\k<q>   # quoted string with named ref

# Python: (?P=name)
(?P<q>["\'])[^\2]*?(?P=q)    # similar (numbered ref still works)

# Practical: matching opening/closing tags
<b>(.*?)</\1>    # WARNING: \1 is "b", but...

# Better: capture tag name
<([a-z][a-z0-9]*)\b[^>]*>[\s\S]*?</\1>

# Find duplicated words
\b(\w+)\s+\1\b   # "the the", "is is"

# Match paired delimiters
(\[)[^\]]*\1\]    # WRONG: matches "[[..[" — use \1 for SAME char

# Date with same separator
(\d{4})([-/])(\d{2})\2(\d{2})  # 2024-01-15 (same separator)
06

비캡처 그룹

기본 비캡처

(?:...)는 캡처를 만들지 않고 그룹화합니다. 선택이나 수량자를 위해 그룹화가 필요하지만 일치한 값이 중요하지 않을 때 사용하세요. 그룹 번호를 예측 가능하게 유지하고 약간 더 빠릅니다.

regex
# (?:pattern) - group without capturing
(?:abc)         # matches "abc", no capture
(?:foo|bar)     # "foo" or "bar", no capture

# Compare
(\d{4})-(\d{2})-(\d{2})     # 3 capture groups
(?:\d{4})-(?:\d{2})-(?:\d{2})  # 0 capture groups (just match)

# When you only care about match/not-match
^(?:Yes|No|Maybe)$       # validate yes/no/maybe
https?://(?:www\.)?\w+  # URL prefix, only domain matters

# Keep capture numbers clean
(?:https?://)?(\w+)    # group 1 = domain (prefix is non-capturing)
vs
(https?://)?(\w+)      # group 1 = protocol, group 2 = domain

# Nested
(?:(?:foo|bar)-)?(\w+)  # group 1 = word (after optional prefix)

수량자와 함께

비캡처 그룹은 일치한 텍스트를 유지하지 않고 하위 패턴을 반복할 때 수량자와 잘 어울립니다. 복잡한 패턴의 특정 부분만 추출할 때 캡처 그룹 번호를 예측 가능하게 유지하는 데 필수입니다.

regex
# Apply quantifier to a non-capturing group
(?:abc)+          # "abc", "abcabc", "abcabcabc"
(?:\d{1,3}\.){3}\d{1,3}  # IPv4: 3 groups of "ddd." then "ddd"
(?:\s*,\s*)      # comma with optional surrounding whitespace
(?:\w+\s+)+\w+\.?  # word sequence (sentence-ish)

# Compare: capturing group + quantifier keeps LAST match only
(\d,)+           # in "1,2,3,", group 1 captures "3," (last)
(?:\d,)+         # same match, no capture

# Optional group with separator
\d{4}(?:-\d{2}){2}    # 2024-01-15 (no captures)
\d{4}(?:[-/]\d{2}){2} # 2024-01-15 or 2024/01/15

# Repeated pattern
(?:\d+\.)*\d+        # version number like 1.2.3

# Multiple non-capturing groups
^(?:Mr|Mrs|Ms|Dr)\.?\s+(?:[A-Z][a-z]+\s?)+$  # full name w/ title

# Avoid extra captures when extracting specific data
https?://(?:www\.)?([\w-]+)\.(?:com|org|net)  # only capture domain

중첩 그룹

비캡처 그룹과 캡처 그룹을 자유롭게 섞으세요. 캡처는 여는 괄호 순서로 번호가 붙지만 비캡처 그룹은 번호를 소비하지 않습니다. 일부 부분만 중요할 때 캡처 번호를 촘촘하게 유지하는 데 사용하세요.

regex
# Mix capturing and non-capturing groups
(?:(\d{4})-(\d{2})-(\d{2}))  # outer non-cap, 3 inner captures
# group 1=year, 2=month, 3=day

# With alternation inside non-capturing
(?:https?|ftp)://([^/]+)  # group 1 = host

# Date with optional time
(\d{4}-\d{2}-\d{2})(?:[ T](\d{2}:\d{2}))?
# group 1 = date, group 2 = optional time

# Practical: parse URL
(?:([^:]+)://)?     # group 1: optional scheme
([^/?#]+)           # group 2: host
(?:/([^?#]*))?      # group 3: optional path
(?:\?([^#]*))?      # group 4: optional query
(?:#(.*))?          # group 5: optional fragment

# CSV-ish parser (simplified)
(?:^|,)(?:"([^"]*)"|([^,]*))
# group 1: quoted field, group 2: unquoted field

# Email-ish
(?:[\w.+-]+)@((?:[\w-]+\.)+[a-z]{2,})
# group 1 = domain (non-capturing group inside)

성능 이점

비캡처 그룹 (?:...)은 엔진이 캡처 텍스트를 저장하지 않으므로 약간 더 빠르고 메모리를 덜 씁니다. 매치당 이점은 작지만 큰 텍스트를 반복하는 빡빡한 루프에서는 중요할 수 있습니다. 캡처 값을 참조할 필요가 없을 때는 항상 사용하세요.

regex
# Non-capturing groups are slightly faster
# They skip storing the matched text

# Microbenchmark concept (Python)
import re, time
text = "a" * 1000

# Capturing version
r1 = re.compile(r"(a)+")
# Non-capturing version
r2 = re.compile(r"(?:a)+")
# Both match same text, but r2 is marginally faster

# More importantly: avoids unnecessary group data
# Use non-capturing when you don't need group(N)

# In hot loops, this matters:
patterns = [
    r"(?:\s*,\s*)",        # non-capturing
    r"(\s*,\s*)",          # capturing (waste if unused)
]

# When extraction IS needed, use capturing:
re.findall(r"(\w+)@(\w+)", "a@b c@d")  # need the captures

# When only matching matters, use non-capturing:
re.search(r"(?:\d{1,3}\.){3}\d{1,3}", text)  # just match test

# Replace with no group reference
re.sub(r"(?:\s)+", "_", "a  b   c")  # "a_b_c" (no groups used)

흔한 사용 사례

비캡처 그룹은 선택 그룹화, 하위 패턴에 수량자 적용, 선택적 섹션, 캡처 번호 유지에 강합니다. 그룹화에는 기본적으로 (?:...)를 쓰고, 실제로 텍스트를 추출하거나 역참조할 때만 ()를 사용하세요.

regex
# 1. Grouping for alternation
(?:cat|dog|bird)s?         # plural animal names
\.(?:jpg|jpeg|png|gif)$    # image extensions
^(?:Mr|Mrs|Ms|Dr)\.\s     # honorifics

# 2. Optional/required sub-patterns
https?://(?:www\.)?       # protocol + optional www
\d{4}(?:-?\d{2}){2}      # date with optional hyphens

# 3. Repeated complex sub-pattern
(?:\d{1,3}\.){3}\d{1,3}  # IPv4
(?:\s*\d+\s*)+,          # comma-separated numbers

# 4. Path-style patterns
(?:/[a-z][\w-]*)+         # URL path like /api/users/123
(?:\.\w+)+               # file.txt.bak (multiple extensions)

# 5. Quoted strings with escapes
"(?:[^"\\]|\\.)*"      # double-quoted with escapes

# 6. Header parsing
^(\w+):\s*(.*)$          # name: value (just capture both)

# 7. Programming keyword + identifier
(?:const|let|var)\s+(\w+)  # only capture the variable name

# 8. CSV with optional quotes
(?:^|,)(?:"([^"]*)"|([^,]*))  # capture quoted OR unquoted
07

전방/후방 탐색

긍정 전방 탐색 (?=)

긍정 전방 탐색 (?=...)은 뒤따르는 내용이 패턴과 일치함을 단언하며 문자를 소비하지 않습니다. 특정 내용이 뒤따를 때만 패턴을 찾거나, 비밀번호 규칙의 '숫자를 포함해야 함' 같은 검증에 유용합니다.

regex
# (?=...) - matches if pattern follows, WITHOUT consuming
foo(?=bar)        # "foo" only if followed by "bar"
\d+(?=px)         # digits only if followed by "px"
\w+(?=@)          # word chars only if followed by "@"

# Lookahead doesn't consume - the next match starts after "foo"
"foobar".match(/foo(?=bar)/)  # match: "foo", index 0
# Next search continues at index 3, "bar" is still there

# Multiple lookaheads (all must match)
\d+(?=\s)(?=.*\bUSD\b)   # digit followed by space AND USD somewhere

# Password: must contain a digit
^(?=.*\d).{8,}$    # at least 8 chars, contains a digit

# Word boundary alternative using lookahead
\w+(?=\W|$)        # word chars until non-word or end

# Find numbers not followed by units
\d+(?!px)(?!em)    # number not followed by px or em

# Capture inside lookahead
(\w+)(?=(\W))     # word + capture the following non-word char

부정 전방 탐색 (?!)

부정 전방 탐색 (?!...)은 뒤따르는 내용이 일치하지 않음을 단언합니다. 특정 단어 제외, 패턴 거부('비밀번호에 password가 들어가면 안 됨'), 특정 내용이 뒤따르지 않을 때만 일치(예: 'q' 뒤에 'u'가 없음)에 흔히 사용합니다.

regex
# (?!...) - matches if pattern does NOT follow
foo(?!bar)        # "foo" only if NOT followed by "bar"
\d+(?!px)         # digits NOT followed by "px"
\w+(?!@\w)        # word NOT followed by @word

# Q-w-o-T: find "q" not followed by "u"
q(?!u)            # matches "q" in "Iraq" but not "quiet"

# Negative lookahead for "not this word"
\b(?!and\b|or\b|not\b)\w+  # any word except "and", "or", "not"

# Number NOT followed by decimal
\d+(?!\.\d)      # "100" in "100 " but not in "100.5"

# Email local part: no consecutive dots
^(?!.*\.\.)[\w.]+@  # reject "a..b@..."

# Password: must NOT contain "password"
^(?!.*password).{8,}$   # 8+ chars, no "password" substring

# Disallow specific file extensions
\.\w+(?!\.(?:exe|bat|dll)$)  # not an executable extension

# Find "cat" not preceded by "scat" (would need lookbehind)
# but here: cat not FOLLOWED by "s" or "egory"
\bcat(?!s|egory)\b

긍정 후방 탐색 (?<=)

긍정 후방 탐색 (?<=...)은 앞선 내용이 일치함을 단언하며 소비하지 않습니다. 특정 내용 뒤에 올 때만 패턴을 찾는 데 사용합니다. 많은 엔진(Java, 구 PCRE, Python < 3.7)은 고정 길이 후방 탐색을 요구하고, JS(ES2018+), .NET, 최신 PCRE는 가변 길이를 허용합니다.

regex
# (?<=...) - matches if pattern PRECEDES (without consuming)
(?<=\$)\d+        # digits preceded by "$"
(?<=#)\w+          # word chars preceded by "#" (hex color)
(?<=Mr\.)\s\w+    # word after "Mr."

# Lookbehind doesn't consume - match starts AFTER the prefix
"$100".match(/(?<=\$)\d+/)  # match: "100", index 2

# Get value after specific label
(?<=total:\s*)\d+\.\d{2}   # number after "total:"

# Find text inside quotes
(?<=")[^"]+(?=")   # content between double quotes

# Currency amount
(?<=USD\s)\d+(?:\.\d{2})?  # number after "USD "

# Capture domain after @
(?<=@)[\w.]+      # domain part of email

# Path segment after /api/
(?<=/api/)[^/?#]+  # resource name in URL

# IMPORTANT: many engines require FIXED-LENGTH lookbehind
# (?<=ab|abc)  -- INVALID in some engines (variable length)
# (?<=ab|cd)   -- OK in most (same length alternatives)
# (?<=\w+)    -- INVALID (variable length) in old engines

# JavaScript (ES2018+), .NET, and newer PCRE allow variable length

부정 후방 탐색 (?<!)

부정 후방 탐색 (?<!...)은 앞선 내용이 일치하지 않음을 단언합니다. 문맥에 따라 매치를 제외할 때 유용합니다(예: '$' 앞에 오지 않는 숫자 찾기, 더 큰 식별자의 일부가 아닌 단어 찾기). 구 엔진에서는 긍정 후방 탐색과 같은 길이 제한이 있습니다.

regex
# (?<!...) - matches if pattern does NOT precede
(?<!\$)\d+        # digits NOT preceded by "$"
(?<!\w)\w+        # word NOT preceded by word char (start of word)
(?<!Mr\.)\s\w+   # space+word NOT after "Mr."

# Find "cat" not preceded by "scat" or "concat"
(?<!s)cat\b       # "cat" not preceded by "s" (matches "cat" alone)

# Number not preceded by a sign
(?<![-+])\d+      # unsigned numbers

# Word not after specific prefix
(?<!un)\w+        # word not preceded by "un"

# Currency validation
(?<!\d)\d{1,3}(?:,\d{3})*(?:\.\d{2})?(?!\d)
# number with thousand separators, not part of larger number

# Prevent matching substring inside larger identifier
(?<![_\w])count\b(?!er)  # "count" not part of "counter"/"_count"

# Remove spaces NOT after periods
text.replace(/(?<!\.)  +/g, " ")
# collapse double spaces unless after a period

# Find "and" not preceded by "&" (avoid matching "&" alone)
(?<!&)\b\w+\b

검증 패턴

전방 탐색은 검증에 탁월합니다. 각 전방 탐색이 같은 시작 위치에서 규칙 하나를 검사합니다. 시작(^)에 여러 전방 탐색을 쌓아 '비밀번호에 대문자, 숫자, 특수 문자 필요' 같은 복합 규칙을 적용하세요. 그다음 주 패턴이 전체 문자열과 일치합니다.

regex
# Lookarounds are perfect for "must contain" / "must not contain"

# Password: 8+ chars, 1+ uppercase, 1+ lowercase, 1+ digit
^(?=.*[A-Z])(?=.*[a-z])(?=.*\d).{8,}$

# Stronger: also require special char
^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[^A-Za-z0-9]).{8,}$

# Must NOT contain "password" (case-insensitive)
^(?!.*password).{8,}$

# Email: must have @ and a dot after it
^(?=[^@]*@[^@]*\.[^@]*$).+$

# US phone: 10 digits possibly with separators
^(?=(?:\D*\d){10}\D*$)[\d\s()-]+$

# IPv4: 4 octets 0-255
^(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)$

# Hex color: 3 or 6 hex digits, optional #
^#?(?:[0-9a-fA-F]{3}){1,2}$

# Date: YYYY-MM-DD with basic validation
^(?!0000)\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])$

# Username: 3-20 chars, alphanumeric + underscore, not starting with digit
^(?=[A-Za-z_])[A-Za-z0-9_]{3,20}$

탐색의 한계

후방 탐색 제한: 많은 엔진(Python <3.7, Java, 구 PCRE)은 고정 길이 패턴을 요구합니다. 최신 엔진(JS ES2018+, .NET, Python 3.7+, PCRE 4.5+)은 가변 길이를 허용합니다. 탐색은 너비가 0이라 커서를 소비하거나 전진시키지 않습니다. 하지만 내부의 캡처 그룹은 실제로 캡처합니다.

regex
# 1. Lookbehind must be FIXED LENGTH in many engines
# Python (before 3.7), Java, older PCRE
(?<=abc|abcd)x    # INVALID - alternatives of different lengths
(?<=abc|def)x     # OK - same length

# Python 3.7+, JS (ES2018+), .NET, PCRE 4.5+ allow variable length
(?<=\w+)x        # OK in modern engines

# 2. Lookbehind CANNOT be unbounded
(?<=.*)x         # INVALID in most engines (no quantifier)

# 3. Capture groups inside lookaround
# DO capture, but the lookahead itself doesn't consume
(\w+)(?=(\W))   # group 1 = word, group 2 = next non-word

# 4. JavaScript lookbehind support (ES2018+)
# Old Safari versions don't support lookbehind
# Use capturing alternative for old browsers:
# Instead of (?<=\$)\d+, use \$(\d+) and use group 1

# 5. Lookarounds are zero-width
# They don't move the cursor
"abc".match(/(?=a)a/)   # match: "a"
"abc".match(/(?=a)b/)   # no match (can't be both a and b)

# 6. Nested lookarounds (legal but complex)
(?=(?:.*\d){3}).+   # must contain at least 3 digits

# 7. Performance: lookarounds can be slow with catastrophic patterns
(?=(a+)+)b           # avoid nested quantifiers in lookahead
08

치환과 교체

기본 교체

교체 문법은 언어마다 다릅니다. JS는 string.replace(regex, str), Python은 re.sub(pattern, repl, string), Java는 String.replaceAll, PHP는 preg_replace를 사용합니다. 모든 매치를 바꾸려면 전역 플래그(g)를 사용하세요. 없으면 첫 번째만 바뀝니다.

regex
# Replace in different languages

# JavaScript
"hello world".replace(/world/, "there")     # "hello there"
"hello world".replace(/o/g, "0")            # "hell0 w0rld"

# Python
import re
re.sub(r"world", "there", "hello world")    # "hello there"
re.sub(r"o", "0", "hello world")            # "hell0 w0rld"

# Java
"hello world".replaceAll("o", "0")          # "hell0 w0rld"

# PHP
preg_replace('/o/', '0', 'hello world')     # "hell0 w0rld"

# Replace first occurrence only
"hello world".replace(/o/, "0")             # "hell0 world" (JS)
re.sub(r"o", "0", "hello world", count=1)   # "hell0 world" (Py)

# Whole-match reference: $& (JS), $0 (Java/PHP), \g<0> (Py)
"abc".replace(/\w/g, "$&!")                # "a!b!c!"

# Python: use a function
re.sub(r"\w", lambda m: m.group(0) + "!", "abc")  # "a!b!c!"

캡처 그룹 교체

교체에서 캡처 그룹을 참조하세요. JS/Java는 $1, $2, Python은 \1, \2 또는 \g<1>(권장), PHP는 $1 또는 \1을 씁니다. 전체 매치는 $&(JS) / $0(Java) / \g<0>(Python)입니다. JS 교체에서 리터럴 $를 쓰려면 $$로 이스케이프하세요.

regex
# Reference captured groups in replacement

# JavaScript: $1, $2, ... for groups; $& for whole match
"2024-01-15".replace(/(\d{4})-(\d{2})-(\d{2})/, "$3/$2/$1")
# Result: "15/01/2024"

# Swap two words
"hello world".replace(/(\w+) (\w+)/, "$2 $1")  # "world hello"

# Python: \1, \2 OR \g<1>, \g<2> (preferred for clarity)
re.sub(r"(\d{4})-(\d{2})-(\d{2})", r"\3/\2/\1", "2024-01-15")
# Result: "15/01/2024"

# Java: $1, $2
"2024-01-15".replaceAll("(\d{4})-(\d{2})-(\d{2})", "$3/$2/$1")

# PHP: $1 or \1
preg_replace('/(\d{4})-(\d{2})-(\d{2})/', '$3/$2/$1', '2024-01-15')

# .NET: ${name} for named groups
# "John".Replace(...) uses ${first} if pattern is (?<first>\w+)

# Use $& (JS) or $0 (Java) for entire match
"hello".replace(/\w/g, "[$&]")    # "[h][e][l][l][o]"

# Literal $ in replacement (JS) - use $$
"price".replace(/price/, "$$100")  # "$100"

명명 그룹 교체

교체에서 명명 그룹 사용: JS는 $<name>, Python은 \g<name>, Java/.NET은 ${name}입니다. PHP는 교체에서 명명 참조를 지원하지 않으므로 번호($1, $2)를 사용하세요. 명명 교체는 특히 그룹이 많은 복잡한 패턴에서 훨씬 읽기 쉽습니다.

regex
# Reference named capture groups in replacement

# JavaScript: $<name>
"2024-01-15".replace(
  /(?<y>\d{4})-(?<m>\d{2})-(?<d>\d{2})/,
  "$<d>/$<m>/$<y>"
)  # "15/01/2024"

# Python: \g<name>
re.sub(
  r"(?P<y>\d{4})-(?P<m>\d{2})-(?P<d>\d{2})",
  r"\g<d>/\g<m>/\g<y>",
  "2024-01-15"
)  # "15/01/2024"

# .NET: ${name}
Regex.Replace("2024-01-15",
  @"(?<y>\d{4})-(?<m>\d{2})-(?<d>\d{2})",
  "${d}/${m}/${y}")

# PHP: \k<name> in pattern, but in replacement use \1 or $1
# (PHP doesn't directly support named backrefs in replacement)
preg_replace(
  '/(?P<y>\d{4})-(?P<m>\d{2})-(?P<d>\d{2})/',
  '$3/$2/$1',  # use numbered refs
  '2024-01-15'
)

# Java: ${name} (Java 7+)
"2024-01-15".replaceAll(
  "(?<y>\d{4})-(?<m>\d{2})-(?<d>\d{2})",
  "${d}/${m}/${y}")

# Swap using named groups
"John Doe".replace(/(?<first>\w+) (?<last>\w+)/, "$<last>, $<first>")
# "Doe, John"

모든 항목 교체

전체 교체 의미는 다릅니다. JS는 /g 플래그가 필요하고(또는 replaceAll 사용), Python의 re.sub는 기본적으로 전체를 바꾸며(count=로 제한), Java의 replaceAll은 정규식/전체, replace는 리터럴/전체입니다. PHP preg_replace는 기본적으로 전체를 바꿉니다($limit 사용). 교체가 첫 번째만 하는지 전체를 하는지 항상 확인하세요.

regex
# Replace ALL matches - critical difference between languages

# JavaScript: needs /g flag for replaceAll behavior
"a-b-c".replace(/-/g, "+")           # "a+b+c"
"a-b-c".replace(/-/, "+")            # "a+b-c" (only first!)

# JavaScript: .replaceAll (ES2021+) requires /g flag
"a-b-c".replaceAll("-", "+")         # "a+b+c" (string pattern)
"a-b-c".replaceAll(/-/g, "+")        # "a+b+c" (regex needs /g)

# Python: re.sub replaces ALL by default
re.sub(r"-", "+", "a-b-c")           # "a+b+c"
# Use count parameter for limited replacement
re.sub(r"-", "+", "a-b-c", count=1)  # "a+b-c"
re.sub(r"-", "+", "a-b-c", count=2)  # "a+b+c" wait, just first 2

# Java: replaceAll takes a regex
"a-b-c".replaceAll("-", "+")         # "a+b+c"
# replaceFirst for just one
"a-b-c".replaceFirst("-", "+")       # "a+b-c"
# Note: String.replace (no "All") does literal replace of ALL
"a-b-c".replace("-", "+")            # "a+b+c" (literal, not regex)

# PHP: preg_replace replaces all by default
preg_replace('/-/', '+', 'a-b-c')    # "a+b+c"
# Use $limit parameter
preg_replace('/-/', '+', 'a-b-c', 1) # "a+b-c"

# Go (noreplaceAll in regexp package)
re := regexp.MustCompile("-")
re.ReplaceAllString("a-b-c", "+")    # "a+b+c"

함수 교체

함수 교체는 대소문자 변환, 산술, 조회 같은 동적 변환을 가능하게 합니다. JS는 함수에 (match, groups, offset, string)을 전달합니다. Python은 매치 객체를 전달하므로 .group(n)으로 캡처에 접근하세요. Java는 Matcher.appendReplacement, PHP는 preg_replace_callback을 사용합니다.

regex
# Use a function for dynamic replacement (JS, Python)

# JavaScript: function receives (match, g1, g2, ..., offset, string)
"hello world".replace(/\w+/g, w => w.toUpperCase())
# "HELLO WORLD"

# Reverse each word
"hello world".replace(/\w+/g, w => w.split("").reverse().join(""))
# "olleh dlrow"

# Increment numbers
"a1 b2 c3".replace(/\d/g, d => parseInt(d) + 1)
# "a2 b3 c4"

# Python: function receives a match object
import re
re.sub(r"\w+", lambda m: m.group(0).upper(), "hello world")
# "HELLO WORLD"

# Use captured groups in Python function
def swap(m):
    return f"{m.group(2)} {m.group(1)}"
re.sub(r"(\w+) (\w+)", swap, "hello world")  # "world hello"

# Java: Matcher.appendReplacement with StringBuilder
Matcher m = Pattern.compile("\\d+").matcher("a1 b2");
StringBuilder sb = new StringBuilder();
while (m.find()) {
    m.appendReplacement(sb, String.valueOf(Integer.parseInt(m.group()) + 10));
}
m.appendTail(sb);  # "a11 b12"

# PHP: preg_replace_callback
preg_replace_callback('/\d+/', function($m) {
    return $m[0] + 10;
}, 'a1 b2');  # "a11 b12"

흔한 교체 패턴

흔한 정규식 교체: 공백 다듬기, 공백 축소, HTML 제거, 대소문자 변환(kebab↔camel↔snake), 민감 데이터 마스킹, 숫자/전화번호 서식, 메타 문자 이스케이프. 각각 캡처 그룹과 교체 참조를 사용해 깔끔한 선언적 변환을 만듭니다.

regex
# Trim leading/trailing whitespace
"  hi  ".replace(/^\s+|\s+$/g, "")        # "hi"

# Collapse multiple spaces into one
"a   b    c".replace(/\s+/g, " ")         # "a b c"

# Replace newlines with <br>
"text\nmore".replace(/\n/g, "<br>")      # "text<br>more"

# Strip HTML tags
"<p>Hello</p>".replace(/<[^>]+>/g, "")     # "Hello"

# Convert kebab-case to camelCase
"my-variable".replace(/-([a-z])/g, (_, c) => c.toUpperCase())
# "myVariable"

# CamelCase to snake_case
"myVar".replace(/([A-Z])/g, "_$1").toLowerCase()
# "my_var"

# Escape regex metacharacters
"1.5".replace(/[.*+?^${}()|[\]\\]/g, "\\$&")  # "1\\.5"

# Mask emails: hide local part
"user@host".replace(/(^.).+(@.+)/, "$1***$2")  # "u***@host"

# Format phone: 1234567890 -> 123-456-7890
"1234567890".replace(/(\d{3})(\d{3})(\d{4})/, "$1-$2-$3")

# URL-encode unsafe characters
"hello world".replace(/[^A-Za-z0-9]/g, c => "%" + c.charCodeAt(0).toString(16))
# "hello%20world"
09

플래그

전역 g

g 플래그(JS)는 match()와 replace()가 첫 번째만이 아니라 모든 매치에서 동작하게 합니다. 참고: g는 lastIndex를 통해 정규식에 상태를 만들므로 같은 정규식 객체를 exec() 호출 간 재사용하면 버그가 생길 수 있습니다. 더 안전한 반복에는 matchAll(ES2020+)을 사용하세요. Python은 re.findall / re.finditer, Java는 replaceAll을 씁니다.

regex
# g flag - match ALL occurrences, not just the first

# JavaScript
"abcabc".match(/a/g)       # ["a", "a"] (all matches)
"abcabc".match(/a/)        # ["a"] (first match only)
"a-b-c".replace(/-/g, "+") # "a+b+c"

# Without /g, replace() only does first match
"a-b-c".replace(/-/, "+")  # "a+b-c"

# With /g, .match returns array of all matches (or null)
"aaa".match(/a/g)          # ["a", "a", "a"]

# WARNING: /g with exec() maintains lastIndex state (gotcha)
const re = /a/g;
re.exec("aaa")  # index 0, lastIndex=1
re.exec("aaa")  # index 1, lastIndex=2
re.exec("aaa")  # index 2, lastIndex=3
re.exec("aaa")  # null, lastIndex=0 (resets)

# Use String.matchAll (ES2020+) for safer iteration
const matches = "aaa".matchAll(/a/g);
for (const m of matches) console.log(m.index);

# Python (re.sub finds all by default; re.findall)
re.findall(r"a", "aaa")    # ["a", "a", "a"]
re.finditer(r"a", "aaa")   # iterator of match objects

# Java: replaceAll = with /g; replaceFirst = without
# PHP: preg_match_all = with /g; preg_match = without
preg_match_all('/a/', 'aaa', $m)  # finds all

대소문자 무시 i

i 플래그는 대소문자를 구분하지 않고 일치시킵니다. 범위가 지정된 대소문자 무시에는 인라인 (?i)를 사용하세요(예: abc(?i)def는 'def'만 대소문자 무시). 대부분의 엔진이 인라인 범위 플래그 (?i:...)를 지원합니다. HTML 태그, 이메일, 대소문자 무시 검색에 흔합니다.

regex
# i flag - ignore case
/abc/i.test("ABC")      # true
/abc/i.test("AbC")      # true

# Match HTML tags case-insensitively
/<div>/i.test("<DIV>")   # true
text.replace(/<br\s*\/?>/gi, "\n")  # <br>, <BR>, <Br/>

# Case-insensitive word match
"Hello hello HELLO".match(/hello/gi)  # ["Hello", "hello", "HELLO"]

# Email is case-insensitive in practice
"[email protected]".match(/^[\w.+-]+@[\w.-]+\.[a-z]{2,}$/i)

# Python
re.search(r"abc", "ABC", re.IGNORECASE)  # match
re.IGNORECASE  # constant
re.I           # shorthand

# Java
"ABC".matches("(?i)abc")  # true (inline flag)
Pattern.compile("abc", Pattern.CASE_INSENSITIVE)

# Inline flags (most engines): (?i)
# (?i)abc  ==  /abc/i
# abc(?i)def  == abc plus case-insensitive def
# (?i:abc)  == case-insensitive abc (PCRE/Java, scoped)

# PHP: '/abc/i'
preg_match('/abc/i', 'ABC')  # 1 (match)

# Go (RE2): always use FlagI
re := regexp.MustCompile("(?i)abc")
re.MatchString("ABC")  # true

# .NET
Regex.Match("ABC", "abc", RegexOptions.IgnoreCase)

여러 줄 m

m 플래그는 ^와 $가 문자열 시작/끝이 아니라 각 줄 경계(줄바꿈)에서 일치하게 합니다. 줄 기반 콘텐츠 처리에 유용합니다. 인라인 형식은 (?m)입니다. 참고: m은 점 .에 영향을 주지 않으며, 그 역할은 s(dotall) 플래그입니다.

regex
# m flag - ^ and $ match start/end of EACH LINE (not just string)

# Without /m: ^ and $ are string-anchored
"line1\nline2".match(/^\w+/)   # ["line1"] (only first line)
"line1\nline2".match(/^\w+/gm) # ["line1", "line2"] (each line)

# Find empty lines
"text\n\nmore".match(/^$/gm)  # [""] (the empty line)

# Comment lines in code
"^#.*" with /gm finds all lines starting with #

# Process each line: replace leading whitespace
"  a\n b\n  c".replace(/^\s+/gm, "")
# "a\nb\nc"

# JavaScript
"hello\nworld".replace(/^/gm, "> ")
# "> hello\n> world"

# Python (re.MULTILINE)
re.findall(r"^\w+", "line1\nline2", re.MULTILINE)
# ["line1", "line2"]
re.M  # shorthand

# Java: Pattern.MULTILINE
Pattern p = Pattern.compile("^\w+", Pattern.MULTILINE)

# Inline: (?m)
# (?m)^\w+  ==  with /m flag

# PHP: '/^\w+/m'
# Go: (?m) inline
# .NET: RegexOptions.Multiline

# IMPORTANT: m does NOT change . (use s flag for that)
# m affects ^ and $; s affects .

닷올 s

s 플래그(dotAll)는 .이 줄바꿈도 일치하게 합니다. JS는 ES2018+, Python은 re.DOTALL/re.S, Java는 Pattern.DOTALL입니다. 혼란스럽게도 .NET은 이를 'Singleline'이라고 부릅니다. m(여러 줄) 플래그와 독립적이라 둘 다 사용할 수 있습니다. /s 없이 이식 가능한 대안은 [\s\S]나 [\d\D]로 줄바꿈을 포함한 모든 문자를 일치시키는 것입니다.

regex
# s flag - dot . matches ALL chars INCLUDING newline

# Without /s: . doesn't match newline
"a\nb".match(/a.b/)    # null
"a\nb".match(/a.b/s)   # ["a\nb"] (with /s)

# Match anything between tags (even across lines)
"<div>a\nb</div>".match(/<div>(.*?)<\/div>/s)
# captures "a\nb"

# JavaScript (ES2018+) - s flag
const re = /<div>[\s\S]*?<\/div>/  # traditional
const re2 = /<div>.*?<\/div>/s        # with /s

# Python: re.DOTALL or re.S
re.search(r"<div>.*?</div>", text, re.DOTALL)

# Inline: (?s)
# (?s).  matches any char including newline

# Java: Pattern.DOTALL
Pattern.compile(".*?", Pattern.DOTALL)

# PHP: '/.*/s'
# Go: (?s) inline
# .NET: RegexOptions.Singleline

# Naming is confusing:
# - JavaScript "s" = "dotAll" (dot matches all)
# - .NET "Singleline" = same (dot matches all)
# - Multiline (m) and Singleline (s) are INDEPENDENT
# - You can use BOTH /ms simultaneously

# Combine m and s
"line1\nline2".replace(/^.*/gms, "X")
# replaces each line entirely with "X"

# Portable alternative (works everywhere): [\s\S] or [\d\D]
/.?[\s\S]*?</tag>/  # portable "any char"

유니코드 u

u 플래그(JS ES6+)는 패턴을 유니코드 코드 포인트로 취급해 서로게이트 쌍 문제를 해결하고 \p{...} 속성 이스케이프를 가능하게 합니다. Python 3는 기본이 유니코드이며(re.ASCII로 제한), PHP는 UTF-8에 /u를 사용합니다. /u가 없으면 JS는 UTF-16 코드 단위로 일치해 이모지/CJK 처리가 깨집니다.

regex
# u flag - treat pattern as Unicode code points (not UTF-16 code units)

# JavaScript (ES6+)
# Without /u: matches UTF-16 code units (broken surrogate pairs)
"𝌆".length             # 2 (surrogate pair)
/^.$/.test("𝌆")         # false (two code units)
/^.$/u.test("𝌆")        # true  (one code point)

# Unicode property escapes (require /u)
/^\p{L}+$/u.test("Hello")   # true (letters)
/\p{Script=Han}/u.test("中文")  # true (CJK characters)
/\p{Emoji}/u.test("👋")       # true

# Case-insensitive Unicode folding
/\w/iu.test("Ω")             # true (Σ/σ/ς equivalence with /iu)

# Python 3: Unicode by default (use re.ASCII for ASCII-only)
re.search(r"\w+", "日本語")  # matches (Unicode default)
re.search(r"\w+", "日本語", re.ASCII)  # ASCII-only

# Python Unicode properties (3.13+ or regex module)
# \p{L} requires regex module or Python 3.13+
import regex  # third-party module
regex.search(r"\p{L}+", "Hello")

# Java: Pattern.UNICODE_CHARACTER_CLASS
Pattern.compile("\\w+", Pattern.UNICODE_CHARACTER_CLASS)
# Java's \w is Unicode by default; flag enables POSIX Unicode classes

# PHP: /u flag for UTF-8 mode
preg_match('/^\p{L}+$/u', 'Hello')  # 1 (Unicode)

# .NET: \p{L} works by default
# Go (RE2): \p{L} works by default

# IMPORTANT: with /u in JS, quantifiers apply to code points
/[😂]{2}/u.test("😂😂")  # true

스티키 y와 확장 x

스티키 플래그 y(JS 전용)는 정확히 lastIndex에서 일치하므로 파서/토크나이저에 유용합니다. 확장 플래그 x는 이스케이프되지 않은 공백을 무시하고 #을 주석 시작으로 취급해 여러 줄로 문서화된 패턴을 작성할 수 있습니다. Python은 re.VERBOSE, PHP/PCRE는 /x, 인라인 형식은 (?x)입니다.

regex
# y flag (sticky) - JS only - matches at lastIndex exactly
const re = /abc/y;
re.lastIndex = 0;
re.test("abcabc")  # true, lastIndex now 3
re.test("abcabc")  # true, lastIndex now 6 (matches at exactly 3)
re.test("abcabc")  # false (would need to start at 6, no chars left)

# Useful for tokenizers (must match in sequence)
function tokenize(str) {
  const tokens = [];
  const ws = /\s*/y;
  const num = /\d+/y;
  const op = /[+\-*/]/y;
  let pos = 0;
  while (pos < str.length) {
    ws.lastIndex = pos; let m = ws.exec(str);
    if (m) pos = ws.lastIndex;
    if (pos >= str.length) break;
    num.lastIndex = pos; m = num.exec(str);
    if (m) { tokens.push(["num", m[0]]); pos = num.lastIndex; continue; }
    op.lastIndex = pos; m = op.exec(str);
    if (m) { tokens.push(["op", m[0]]); pos = op.lastIndex; continue; }
    throw new Error("Unexpected at " + pos);
  }
  return tokens;
}

# x flag (extended) - whitespace in pattern ignored, # starts comment
# JavaScript: ES2025+ proposal; widely supported in other engines

# Python (re.VERBOSE)
pattern = r"""
  \d{4}      # year
  -           # separator
  \d{2}      # month
  -           # separator
  \d{2}      # day
"""
re.match(pattern, "2024-01-15", re.VERBOSE)

# PHP: /x flag
preg_match('/
  \d{4}    # year
  -
  \d{2}    # month
/x', '2024-01')

# Inline: (?x)
# (?x)\d{4}-\d{2}  # comment allowed

# To match literal whitespace in /x mode, escape: \  or use [ ]
# \ \t\n all still work; just unescaped space/tab are ignored
10

흔한 패턴

이메일

이메일 정규식은 악명 높게 어렵습니다. 전체 RFC 5322 정규식은 거대합니다. 대부분의 운영 코드는 흔한 잘못된 형식을 잡는 단순화된 패턴을 사용합니다. 유일한 진짜 검증은 확인 링크를 담은 이메일을 보내는 것입니다. 명백히 잘못된 형식은 거부하되 경계 사례에는 관대하세요.

regex
# Simplified email (good for most uses)
^[\w.+-]+@[\w.-]+\.[a-zA-Z]{2,}$

# More strict
^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$

# RFC 5322 (simplified - the actual RFC is much more complex)
^(?:[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+
   (?:\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*)
  @
  (?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+
  [a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$

# JavaScript
const emailRe = /^[\w.+-]+@[\w.-]+\.[a-zA-Z]{2,}$/;
emailRe.test("[email protected]")      # true
emailRe.test("[email protected]")  # true

# Python
import re
re.match(r"^[\w.+-]+@[\w.-]+\.[a-z]{2,}$", "[email protected]", re.I)

# Practical note: the only true validation is sending an email.
# Reject clearly invalid formats, but accept edge cases.

# Common TLD length: 2-24 chars (newer TLDs can be long)
^[\w.+-]+@[\w.-]+\.[a-zA-Z]{2,24}$

URL

URL 정규식은 단순한 것(https?://...)부터 RFC 준수 복잡한 것까지 다양합니다. 운영 환경에서는 내장 URL 클래스(JS)나 urllib.parse(Python)를 권장합니다. 정규식을 쓸 때는 scheme/host/port/path/query/fragment를 따로 캡처해 전체 파싱을 하세요. 도메인 정규식: 레이블은 최대 63자, TLD는 2자 이상입니다.

regex
# Basic URL pattern
^https?://[\w.-]+(?:\.[a-z]{2,})?(:\d+)?(?:/\S*)?$

# More complete URL parser
^(?:(\w+)://)?              # 1: scheme
([^/:?#]+)                  # 2: host
(?::(\d+))?                 # 3: port
([^?#]*)                    # 4: path
(?:\?([^#]*))?              # 5: query
(?:#(.*))?                  # 6: fragment
$

# JavaScript URL parsing
const urlRe = /^(https?):\/\/([^/:?#]+)(?::(\d+))?
              ([^?#]*)(?:\?([^#]*))?(?:#(.*))?$/ix;
const m = "https://example.com:8080/path?q=1#top".match(urlRe);
// m[1]="https", m[2]="example.com", m[3]="8080",
// m[4]="/path", m[5]="q=1", m[6]="top"

# Python
import re
url_re = re.compile(r'''
  ^(?P<scheme>https?)://
  (?P<host>[^/:?#]+)
  (?::(?P<port>\d+))?
  (?P<path>[^?#]*)
  (?:\?(?P<query>[^#]*))?
  (?:\#(?P<frag>.*))?
  $''', re.VERBOSE | re.IGNORECASE)

# Match domain only
^(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$

# Validate URL using built-in URL class (JS)
try { new URL(input); } catch { /* invalid */ }

전화번호

전화번호 형식은 국가마다 크게 다릅니다. 미국은 10자리이며 선택적 구분자/국가 코드가 있습니다. 국제 E.164는 + 뒤에 최대 15자리입니다. 실제 검증에는 먼저 정규화(비숫자 제거)한 뒤 자릿수와 접두사를 확인하세요. 운영 환경에서는 정규식보다 전화 API/라이브러리가 더 신뢰할 만합니다.

regex
# US phone: 123-456-7890, (123) 456-7890, 1234567890
^(?:\+1[-.\s]?)?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}$

# Capture components
^(?:\+1[-.\s]?)?\(?\(?(\d{3})\)?[-.\s]?(\d{3})[-.\s]?(\d{4})$

# International (E.164): +[country][number], max 15 digits
^\+[1-9]\d{1,14}$

# China phone: 11 digits starting with 1
^1[3-9]\d{9}$

# UK phone: 0XXXXXXXXXX or +44XXXXXXXXXX
^(?:0|\+44)\d{10}$

# Generic international (loose)
^\+?[\d\s().-]{7,}$

# JavaScript
const phoneRe = /^(?:\+1[-.\s]?)?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}$/;
phoneRe.test("(123) 456-7890")  # true
phoneRe.test("123-456-7890")    # true
phoneRe.test("1234567890")      # true

# Python: extract phone from text
re.findall(r"\b\d{3}[-.]?\d{3}[-.]?\d{4}\b", text)

# Format phone: 1234567890 -> (123) 456-7890
"1234567890".replace(/(\d{3})(\d{3})(\d{4})/, "($1) $2-$3")

IP 주소

IPv4 정규식은 선택을 사용해 옥텟마다 0-255를 강제합니다. 250-255는 25[0-5], 200-249는 2[0-4]\d, 0-199는 1?\d?\d입니다. IPv6는 훨씬 복잡합니다(:: 축약 포함). 사설 IP 감지: 10.x, 172.16-31.x, 192.168.x. 견고한 파싱에는 ipaddress 모듈(Python)이나 net(JS)을 사용하세요.

regex
# IPv4: four octets 0-255
^(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}
 (?:25[0-5]|2[0-4]\d|1?\d?\d)$

# Explanation:
# 25[0-5]      -> 250-255
# 2[0-4]\d     -> 200-249
# 1?\d?\d     -> 0-199 (1? optional leading 1, \d? optional tens)

# Python
import re
ipv4_re = re.compile(
    r'^(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)$'
)
ipv4_re.match("192.168.1.1")   # match
ipv4_re.match("256.0.0.1")     # None (256 > 255)

# Extract IPv4 from text
re.findall(r'\b(?:\d{1,3}\.){3}\d{1,3}\b', text)

# IPv6 (simplified)
^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$
# (:: shorthand, mixed notation are more complex)

# JavaScript
const ipv4 = /^(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)$/;
ipv4.test("0.0.0.0")       # true
ipv4.test("255.255.255.255") # true
ipv4.test("256.0.0.0")     # false

# Convert IP to number
"192.168.1.1".split(".").reduce((acc, o) => (acc << 8) + +o, 0) >>> 0

# Private IP ranges
^(?:10\.|172\.(?:1[6-9]|2\d|3[01])\.|192\.168\.)

16진 색상

16진 색상 정규식: # 뒤에 3자리 또는 6자리 16진 숫자. {3,6}은 4, 5자리도 허용하므로 주의하세요. 더 나은 방법은 (?:[0-9a-fA-F]{3}){1,2}로 정확히 3자리 또는 6자리를 강제하는 것입니다. 8자리(RGBA) 지원에는 [0-9a-fA-F]{3,4} 또는 {8}을 사용하세요. CSS 색상은 hsl(), rgb(), 이름일 수도 있으므로 운영 환경에서는 CSS 파서를 사용하세요.

regex
# Hex color: #RGB or #RRGGBB
^#?(?:[0-9a-fA-F]{3}){1,2}$

# Strict with #
^#(?:[0-9a-fA-F]{3}){1,2}$

# With optional alpha: #RGBA or #RRGGBBAA
^#(?:[0-9a-fA-F]{3,4}){1,2}$

# Capture RGB components
^#([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$

# JavaScript
const hexRe = /^#(?:[0-9a-fA-F]{3}){1,2}$/;
hexRe.test("#fff")       # true
hexRe.test("#FFAABB")    # true
hexRe.test("#12AB56")    # true
hexRe.test("#GGG")       # false
hexRe.test("fff")        # false (no #)

# Allow without #
const hexLoose = /^#?[0-9a-fA-F]{3}(?:[0-9a-fA-F]{3})?$/

# Extract hex colors from CSS
const css = "color: #fff; background: #123456;";
const colors = css.match(/#[0-9a-fA-F]{3,6}/g);
// ["#fff", "#123456"]

# Convert #RGB to #RRGGBB
"#abc".replace(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/i, "#$1$1$2$2$3$3")
// "#aabbcc"

# Python
import re
re.match(r"^#(?:[0-9a-fA-F]{3}){1,2}$", "#abc123")

우편번호

우편번호 형식은 국가마다 다릅니다. 미국 ZIP은 5자리에 선택적 +4, 캐나다는 문자-숫자-문자 공백 숫자-문자-숫자, 영국 우편번호는 복잡합니다. 국가의 공식 형식으로 검증하세요. 다국가 앱에서는 하나의 거대한 패턴보다 국가별 정규식을 선택하세요.

regex
# US ZIP: 12345 or 12345-6789
^\d{5}(?:-\d{4})?$

# Canada postal: A1A 1A1 (letter digit letter space digit letter digit)
^[A-Za-z]\d[A-Za-z][ -]?\d[A-Za-z]\d$

# UK postcode (simplified)
^[A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}$

# China postal code: 6 digits
^\d{6}$

# Germany: 5 digits
^\d{5}$

# France: 5 digits
^\d{5}$

# Australia: 4 digits
^\d{4}$

# JavaScript
const zipRe = /^\d{5}(?:-\d{4})?$/;
zipRe.test("12345")        # true
zipRe.test("12345-6789")   # true
zipRe.test("1234")         # false

# Canada postal
const caRe = /^[A-Za-z]\d[A-Za-z][ -]?\d[A-Za-z]\d$/;
caRe.test("M5V 2H1")       # true
caRe.test("m5v2h1")        # true

# Python
import re
re.match(r"^\d{5}(?:-\d{4})?$", "12345-6789")  # match

# Format ZIP: 123456789 -> 12345-6789
"123456789".replace(/(\d{5})(\d{4})/, "$1-$2")
11

비밀번호 검증

최소 길이

최소 길이는 가장 중요한 비밀번호 규칙입니다. 최신 지침(NIST)은 최소 8자 이상을 권장하며 더 긴 패스프레이즈(12-16자 이상)를 장려합니다. 복합 규칙에는 전방 탐색을 조합하세요. (?=.{8,}$)는 소비 없이 길이를 단언하므로 다른 규칙도 시작부터 검사할 수 있습니다.

regex
# At least 8 characters
^.{8,}$

# At least 12 characters (modern recommendation)
^.{12,}$

# Between 8 and 128 characters
^.{8,128}$

# Using lookahead (allows combining with other rules)
^(?=.{8,}$).*$

# JavaScript
const lenRe = /^.{8,}$/;
lenRe.test("short")        # false
lenRe.test("longenough")   # true

# Python
import re
bool(re.match(r"^.{8,}$", "longenough"))  # True

# Allow any character including newlines (use s flag or [\s\S])
# /^.{8,}$/s  matches multi-line password

# Common: 8+ with at least one of each type (lookaheads)
^(?=.{8,}$)             # at least 8 chars
(?=.*[a-z])             # at least one lowercase
(?=.*[A-Z])             # at least one uppercase
(?=.*\d)               # at least one digit
(?=.*[^A-Za-z0-9])      # at least one special char
.*$

대문자 요구

전방 탐색 (?=.*[A-Z])로 대문자를 요구합니다. N개 대문자는 (?=(?:.*[A-Z]){N})입니다. 유니코드 대문자(그리스, 키릴 등)에는 u 플래그(JS)와 함께 \p{Lu}를 쓰거나 Python의 regex 모듈을 사용하세요. 전방 탐색 없이 별도로 test/카운트하면 코드가 더 깔끔합니다.

regex
# Must contain at least one uppercase letter
^(?=.*[A-Z]).*$

# Must contain at least one uppercase, 8+ chars
^(?=.*[A-Z]).{8,}$

# At least two uppercase letters
^(?=(?:.*[A-Z]){2}).*$

# JavaScript
const upperRe = /^(?=.*[A-Z]).{8,}$/;
upperRe.test("password")        # false (no uppercase)
upperRe.test("Password")        # true
upperRe.test("PASSWORD")        # true

# Python
import re
bool(re.match(r"^(?=.*[A-Z]).{8,}$", "Password1"))  # True

# Count uppercase letters
const uppers = (pwd) => (pwd.match(/[A-Z]/g) || []).length;
uppers("PassWord")  # 2

# Allow Unicode uppercase (with /u flag in JS)
const unicodeUpper = /^(?=.*\p{Lu}).+$/u;
unicodeUpper.test("Ωμέγα")  # true (Ω is uppercase Greek)

# Python Unicode uppercase
re.search(r"\p{Lu}", "Ωμέγα", regex.UNICODE)  # needs 'regex' module

# .NET: \p{Lu} for any uppercase letter
# Java: \p{Lu} works with Pattern.UNICODE_CHARACTER_CLASS

# Without lookahead: just count
if (/[A-Z]/.test(password)) { /* has uppercase */ }

숫자 요구

(?=.*\d)로 숫자를 요구합니다. N개 숫자는 (?=(?:.*\d){N})입니다. \d는 기본 모드에서 유니코드 숫자와 일치하므로 ASCII만 원하면 [0-9]를 사용하세요. 많은 개발자는 전방 탐색을 쌓기보다 별도 test() 호출이 더 명확하다고 봅니다. 각 규칙을 하나의 불리언 검사로 읽을 수 있기 때문입니다.

regex
# Must contain at least one digit
^(?=.*\d).*$

# At least one digit, 8+ chars
^(?=.*\d).{8,}$

# At least three digits
^(?=(?:.*\d){3}).*$

# JavaScript
const digitRe = /^(?=.*\d).{8,}$/;
digitRe.test("password")        # false (no digit)
digitRe.test("password1")       # true
digitRe.test("pass1word2")      # true

# Count digits
const digits = (pwd) => (pwd.match(/\d/g) || []).length;
digits("pass12word")  # 2

# Python
import re
bool(re.match(r"^(?=.*\d).{8,}$", "password1"))  # True

# Unicode digits (e.g., Arabic-Indic digits)
/^.*\p{N}/u.test("password١")  # true (١ is Arabic-Indic 1)

# ASCII-only digits explicitly
^(?=.*[0-9]).*$

# Common password rule: must contain letter AND digit
^(?=.*[A-Za-z])(?=.*\d).{8,}$

# Alphanumeric only (no special chars)
^[A-Za-z0-9]{8,}$

# Without regex
const hasDigit = (s) => /\d/.test(s);
const hasLetter = (s) => /[A-Za-z]/.test(s);
if (hasDigit(pwd) && hasLetter(pwd) && pwd.length >= 8) { /* OK */ }

특수 문자

(?=.*[^A-Za-z0-9])로 특수 문자를 요구합니다. 참고: 공백도 특수 문자로 계산되므로 필요하면 허용 목록으로 명시적으로 제외하세요. 많은 사이트가 안전한 허용 목록(예: [!@#$%^&*])으로 제한합니다. 공백을 금지하려면 항상 별도로 확인하세요.

regex
# Must contain at least one special (non-alphanumeric) char
^(?=.*[^A-Za-z0-9]).*$

# Or explicit list of special chars
^(?=.*[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>/?]).*$

# At least one special, 8+ chars
^(?=.*[^A-Za-z0-9]).{8,}$

# JavaScript
const specialRe = /^(?=.*[^A-Za-z0-9]).{8,}$/;
specialRe.test("password")     # false
specialRe.test("password!")    # true
specialRe.test("pass word")    # true (space is non-alphanumeric!)

# To exclude space from "special":
^(?=.*[!@#$%^&*\-_=+]).*$

# Python
import re
bool(re.match(r"^(?=.*[^A-Za-z0-9]).{8,}$", "Password1!"))  # True

# Count special characters
const specials = (pwd) => (pwd.match(/[^A-Za-z0-9]/g) || []).length;

# Common allow-list for special chars in passwords
const ALLOWED_SPECIAL = /[!@#$%^&*\-_=+?]/;
const hasAllowedSpecial = (pwd) => ALLOWED_SPECIAL.test(pwd);

# Disallow whitespace entirely
^(?=\S*$).{8,}$                # no whitespace, 8+ chars
^(?!.*\s).{8,}$                # equivalent

# Without regex
const hasSpecial = (s) => /[^A-Za-z0-9]/.test(s);
const noWhitespace = (s) => !/\s/.test(s);

복합 검증

복합 규칙은 시작에 전방 탐색을 쌓으세요. 각 전방 탐색이 같은 위치에서 조건 하나를 단언합니다. 유지보수성 측면에서는 하나의 거대한 정규식보다 별도 test() 호출이 더 명확할 수 있습니다. NIST 최신 지침: 길이(12자 이상)를 우선하고, 모든 출력 가능 문자를 허용하며, 알려진 유출 비밀번호와 대조하세요.

regex
# Combined password rule:
# - 8+ chars
# - 1+ lowercase
# - 1+ uppercase
# - 1+ digit
# - 1+ special char
^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^A-Za-z0-9]).{8,}$

# Stronger: 12+ chars, 2+ digits
^(?=.*[a-z])(?=.*[A-Z])(?=(?:.*\d){2})(?=.*[^A-Za-z0-9]).{12,}$

# JavaScript
const strongPwd = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^A-Za-z0-9]).{8,}$/;
strongPwd.test("Password1!")   # true
strongPwd.test("password")     # false (no upper, digit, special)
strongPwd.test("PASSWORD1!")   # false (no lower)

# Python
import re
STRONG = re.compile(
    r"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^A-Za-z0-9]).{8,}$"
)
bool(STRONG.match("Password1!"))  # True

# Readable alternative: separate checks (often clearer)
function validatePassword(pwd) {
  const checks = {
    length: pwd.length >= 8,
    lower: /[a-z]/.test(pwd),
    upper: /[A-Z]/.test(pwd),
    digit: /\d/.test(pwd),
    special: /[^A-Za-z0-9]/.test(pwd),
    noWhitespace: !/\s/.test(pwd),
  };
  return Object.values(checks).every(Boolean) ? checks : null;
}

# Disallow common weak passwords
^(?!password|123456|qwerty|letmein).{8,}$

# NIST guidance: focus on length, allow all char types,
# check against breach databases (haveibeenpwned API)
12

날짜 매칭

YYYY-MM-DD

정규식은 형식(YYYY-MM-DD, 월 01-12, 일 01-31)을 검증할 수 있지만 의미상 유효성(2월 30일, 윤년)은 검증하지 못합니다. 실제 검증에는 Date(JS)나 datetime(Python)을 사용하세요. 캡처 그룹으로 연/월/일을 추출해 추가 처리할 수 있습니다. 모호하지 않은 날짜에는 ISO 8601 형식을 사용하세요.

regex
# Basic: 4 digits, dash, 2 digits, dash, 2 digits
^\d{4}-\d{2}-\d{2}$

# With basic validation (month 01-12, day 01-31)
^\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])$

# Disallow year 0000
^(?!0000)\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])$

# JavaScript
const dateRe = /^(?!0000)\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])$/;
dateRe.test("2024-01-15")   # true
dateRe.test("2024-13-01")   # false (month 13)
dateRe.test("2024-02-31")   # true (regex doesn't know Feb has 28 days)

# Capture components
^(\d{4})-(\d{2})-(\d{2})$
"2024-01-15".match(/^(\d{4})-(\d{2})-(\d{2})$/)
// ["2024-01-15", "2024", "01", "15"]

# Python
import re
m = re.match(r"^(\d{4})-(\d{2})-(\d{2})$", "2024-01-15")
year, month, day = m.groups()

# Use Date for real validation
const d = new Date("2024-01-15");
if (isNaN(d.getTime())) { /* invalid */ }

# Python: datetime for real validation
from datetime import date
try: date(2024, 1, 15)
except ValueError: pass  # invalid

DD/MM/YYYY

DD/MM/YYYY(유럽)와 MM/DD/YYYY(미국)는 똑같아 보이므로 모호성이 실제 문제입니다. 저장/교환에는 항상 ISO 8601(YYYY-MM-DD)을 사용하세요. 정규식으로 일/월/연을 캡처해 재포맷할 수 있습니다. 실제 검증(2월 29일, 윤년, 월별 일수)에는 날짜 라이브러리가 필요합니다.

regex
# DD/MM/YYYY with basic validation
^(?:0[1-9]|[12]\d|3[01])/(?:0[1-9]|1[0-2])/\d{4}$

# Capture day, month, year
^(\d{2})/(\d{2})/(\d{4})$

# With separators: / or - or .
^(\d{1,2})[/-](\d{1,2})[/-](\d{4})$

# JavaScript
const re = /^(\d{1,2})[/-](\d{1,2})[/-](\d{4})$/;
const m = "15/01/2024".match(re);
// m[1]="15", m[2]="01", m[3]="2024"

# US format MM/DD/YYYY
^(?:0[1-9]|1[0-2])/(?:0[1-9]|[12]\d|3[01])/\d{4}$

# Allow 1 or 2 digit day/month
^(\d{1,2})/(\d{1,2})/(\d{4})$

# Capture and reorder: DD/MM/YYYY -> YYYY-MM-DD
"15/01/2024".replace(/^(\d{2})\/(\d{2})\/(\d{4})$/, "$3-$2-$1")
// "2024-01-15"

# Python
import re
re.sub(r"^(\d{2})/(\d{2})/(\d{4})$", r"\3-\2-\1", "15/01/2024")
# "2024-01-15"

# Detect format ambiguity: 01/02/2024 - is it Jan 2 or Feb 1?
# Use ISO 8601 (YYYY-MM-DD) for unambiguous storage

시간 형식

시간 정규식: 시는 00-23(12시간제는 01-12), 분/초는 00-59. 시간에는 선택([01]\d|2[0-3])을 사용하세요. 저장에는 항상 ISO 8601(선택적 시간대를 포함한 HH:MM:SS)을 사용하세요. 실제 시간 산술에는 Date/datetime을 사용하고, 정규식은 형식 검증에만 쓰세요.

regex
# 24-hour: HH:MM
^([01]\d|2[0-3]):[0-5]\d$

# 24-hour: HH:MM:SS
^([01]\d|2[0-3]):[0-5]\d:[0-5]\d$

# 12-hour with AM/PM
^(0?[1-9]|1[0-2]):[0-5]\d(?:\s?[AP]M)?$

# Capture HH, MM, SS
^([01]\d|2[0-3]):([0-5]\d):([0-5]\d)$

# With milliseconds
^([01]\d|2[0-3]):[0-5]\d:[0-5]\d\.\d{3}$

# JavaScript
const time24 = /^([01]\d|2[0-3]):[0-5]\d$/;
time24.test("23:59")  # true
time24.test("24:00")  # false
time24.test("12:30")  # true

const time12 = /^(0?[1-9]|1[0-2]):[0-5]\d\s?[AP]M$/i;
time12.test("1:30 PM")  # true
time12.test("12:00am")  # true

# Python
import re
re.match(r"^([01]\d|2[0-3]):[0-5]\d:[0-5]\d$", "12:30:45")

# ISO 8601 duration: PT1H30M
^PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?$

# Time zone offset: +HH:MM or -HH:MM
[+-]([01]\d|2[0-3]):?[0-5]\d

# Combined date and time (ISO 8601)
^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:Z|[+-]\d{2}:?\d{2})?$

ISO 8601 날짜시간

ISO 8601은 날짜/시간의 국제 표준입니다. YYYY-MM-DDTHH:MM:SS에 선택적 소수 초와 시간대(Z는 UTC, 또는 ±HH:MM)가 붙습니다. 운영 환경 파싱에는 Date(JS)나 datetime.fromisoformat(Python 3.7+)을 사용하세요. 정규식은 형식 검증 전용입니다.

regex
# ISO 8601 date
^\d{4}-\d{2}-\d{2}$

# ISO 8601 date and time (basic)
^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:Z|[+-]\d{2}:\d{2})?$

# With optional milliseconds
^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})?$

# JavaScript - use built-in Date parsing
const d = new Date("2024-01-15T10:30:00Z");
if (!isNaN(d.getTime())) { /* valid ISO */ }

# Validate ISO 8601 strictly
const isoRe = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{3})?(?:Z|[+-]\d{2}:\d{2})$/;
isoRe.test("2024-01-15T10:30:00Z")           # true
isoRe.test("2024-01-15T10:30:00.123Z")       # true
isoRe.test("2024-01-15T10:30:00+08:00")      # true
isoRe.test("2024-01-15 10:30:00")            # false (T required)

# Python - use datetime.fromisoformat (3.7+)
from datetime import datetime
try:
    datetime.fromisoformat("2024-01-15T10:30:00")
except ValueError:
    pass  # invalid

# Capture date and time components
^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(Z|[+-]\d{2}:\d{2})?$

# Week date: 2024-W03-1 (year-week-weekday)
^\d{4}-W\d{2}-\d$

# Ordinal date: 2024-015 (year-day of year)
^\d{4}-\d{3}$

구성 요소 캡처

캡처 그룹으로 처리할 날짜 구성 요소를 추출할 수 있습니다. 명명 그룹(Python의 (?P<name>...), JS의 (?<name>...))을 쓰면 숫자 참조보다 코드가 훨씬 읽기 쉽습니다. JS Date 생성자에는 월을 정수로 바꾼 뒤 1을 빼야 합니다(월이 0부터 시작).

regex
# Capture year, month, day from YYYY-MM-DD
^(\d{4})-(\d{2})-(\d{2})$
# Groups: 1=year, 2=month, 3=day

# JavaScript
const m = "2024-01-15".match(/^(\d{4})-(\d{2})-(\d{2})$/);
const [_, year, month, day] = m;
// year="2024", month="01", day="15"

# Named groups (clearer)
const m2 = "2024-01-15".match(
  /^(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})$)/
);
m2.groups.year  // "2024"
m2.groups.month // "01"
m2.groups.day   // "15"

# Python with named groups
import re
m = re.match(r"(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})",
             "2024-01-15")
m.group("year")   # "2024"
m.groupdict()     # {"year": "2024", "month": "01", "day": "15"}

# Reformat date: YYYY-MM-DD -> DD/MM/YYYY
"2024-01-15".replace(
  /^(?<y>\d{4})-(?<m>\d{2})-(?<d>\d{2})$/,
  "$<d>/$<m>/$<y>"
)
// "15/01/2024"

# Python
re.sub(r"(\d{4})-(\d{2})-(\d{2})", r"\3/\2/\1", "2024-01-15")
# "15/01/2024"

# Validate and extract date from text
const text = "Meeting on 2024-01-15 at 10:30";
const [_, y, mo, d] = text.match(/(\d{4})-(\d{2})-(\d{2})/);
// y="2024", mo="01", d="15"

# Convert to Date object
const d = new Date(+y, +mo - 1, +d);  # months are 0-indexed
13

숫자 매칭

정수

정수 정규식: ^[+-]?\d+$(부호 선택). 천 단위 구분자는 ^\d{1,3}(?:,\d{3})*$로 세 자리 그룹을 강제합니다. 유럽 형식은 점/공백을 구분자로 씁니다. 16진/8진/2진은 0x/0o/0b 접두사를 사용합니다(구 언어의 8진수는 0만 쓰기도 함).

regex
# Positive integers
^\d+$

# Optional sign
^[+-]?\d+$

# Negative only
^-\d+$

# With thousand separators (US/EU: comma)
^[+-]?\d{1,3}(?:,\d{3})*$

# JavaScript
const intRe = /^[+-]?\d+$/;
intRe.test("12345")    # true
intRe.test("-1")       # true
intRe.test("+42")      # true
intRe.test("3.14")     # false

# With commas
const commaInt = /^[+-]?\d{1,3}(?:,\d{3})*$/;
commaInt.test("1,234")        # true
commaInt.test("12,345,678")   # true
commaInt.test("1234")         # false (needs comma)

# Allow comma-less too
^[+-]?(?:\d{1,3}(?:,\d{3})*|\d+)$

# Python
import re
re.match(r"^[+-]?\d+$", "12345")  # match

# Strip commas before parsing
"1,234,567".replace(/,/g, "")  # "1234567"
int("1,234,567".replace(",", ""))  # 1234567

# Hex integer
^0x[0-9a-fA-F]+$

# Octal
^0o?[0-7]+$

# Binary
^0b[01]+$

소수

소수 정규식은 주의가 필요합니다. 앞 점(.5)을 허용할까요? 뒤 점(1.)은요? 정수부는 선택인가요? 흔한 형식 ^[+-]?\d+(?:\.\d+)?$는 정수부를 요구하고 소수부는 선택입니다. 통화에는 소수 자릿수를 고정하세요(예: {2}).

regex
# Basic decimal: digits.digits
^\d+\.\d+$

# Optional integer or fractional part
^\d+\.?\d*$        # 1, 1., 1.5
^\d*\.?\d+$        # .5, 1.5, 1
^\d+\.\d+|\d+$    # integer or decimal

# With optional sign
^[+-]?(?:\d+\.\d+|\d+)$

# JavaScript
const decRe = /^[+-]?(?:\d+\.\d+|\d+)$/;
decRe.test("3.14")     # true
decRe.test("-0.5")     # true
decRe.test("1")        # true
decRe.test(".5")       # false (requires leading digit)

# Allow leading dot
^[+-]?(?:\d+\.?\d*|\.\d+)$

# Fixed decimal places (e.g., 2)
^[+-]?\d+\.\d{2}$

# With thousand separators
^[+-]?\d{1,3}(?:,\d{3})*\.\d+$

# Avoid trailing dot
^[+-]?\d+(?:\.\d+)?$

# Extract decimals from text
"The price is 3.14 dollars".match(/-?\d+\.\d+/)
// ["3.14"]

# Python
import re
re.findall(r"-?\d+\.\d+", "Pi is 3.14, e is 2.72")  # ['3.14', '2.72']

# Strict: 1-6 decimal places
^\d+\.\d{1,6}$

음수

음수 정규식: ^-?\d+$는 선택적 마이너스를 허용합니다. 엄격한 음수는 ^-\d+$입니다. 텍스트에서 추출할 때 주의하세요. 'co-operative'의 하이픈이 일치할 수 있습니다. 단어 경계(\b)를 쓰거나 마이너스 앞에 공백을 요구해 오탐을 피하세요.

regex
# Optional minus sign
^-?\d+$

# Optional + or -
^[+-]?\d+$

# Required minus
^-\d+$

# With decimal
^-?\d+\.\d+$

# JavaScript
const negRe = /^-?\d+$/;
negRe.test("-123")   # true
negRe.test("123")    # true (zero or one minus)
negRe.test("--1")    # false

# Strict negative integer
const strictNeg = /^-\d+$/;
strictNeg.test("-1")    # true
strictNeg.test("0")     # false
strictNeg.test("-0")    # true (technically -0)

# Exclude negative zero
^-(?!0+$)\d+$

# Allow scientific notation with sign
^[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?$

# Extract signed numbers from text
"Temperature: -5 to +10 degrees".match(/[+-]?\d+/g)
// ["-5", "+10"]

# Python
import re
re.findall(r"-?\d+", "loss: -100, gain: 50")  # ['-100', '50']

# Avoid matching minus as text hyphen
# Use word boundary or whitespace before
\s-?\d+      # minus must follow whitespace
\b-?\d+\b   # word boundary

# Currency with optional negative
^\$?-?\d+(?:\.\d{2})?$  # $-5.00 or -5.00 or $5.00

과학적 표기법

과학적 표기법: 가수(선택적 소수 포함), 'e' 또는 'E', 선택적 부호, 지수 숫자. 파싱에는 parseFloat(JS)나 float(Python)를 사용하세요. 과학적 표기법을 기본 처리합니다. 필요하면 캡처 그룹으로 가수와 지수에 따로 접근할 수 있습니다.

regex
# Scientific notation: mantissa e exponent
^[+-]?(?:\d+\.?\d*|\.\d+)[eE][+-]?\d+$

# Examples: 1e10, -2.5E-3, 6.022e23, 1.5E+10

# JavaScript
const sciRe = /^[+-]?(?:\d+\.?\d*|\.\d+)[eE][+-]?\d+$/;
sciRe.test("1e10")        # true
sciRe.test("-2.5E-3")     # true
sciRe.test("6.022e23")    # true
sciRe.test("1.5E+10")     # true
sciRe.test("1e")          # false (no exponent)

# Allow integer or decimal without exponent too
^[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?$

# Capture mantissa and exponent
^([+-]?(?:\d+\.?\d*|\.\d+))[eE]([+-]?\d+)$

const m = "-2.5E-3".match(/^([+-]?(?:\d+\.?\d*|\.\d+))[eE]([+-]?\d+)$/);
// m[1]="-2.5" (mantissa), m[2]="-3" (exponent)

# Convert to number
parseFloat("6.022e23")  # 6.022e+23
Number("1.5E+10")       # 15000000000

# Python
import re
re.match(r"^[+-]?(?:\d+\.?\d*|\.\d+)[eE][+-]?\d+$", "-2.5E-3")
float("-2.5E-3")  # -0.0025

# Extract scientific numbers from text
re.findall(r"[-+]?\d+\.?\d*[eE][-+]?\d+", "Avogadro: 6.022e23")
# ['6.022e23']

# Engineering notation (exponent multiple of 3)
# Hard to enforce via regex; better to validate after parsing
# Examples: 1.5e3, 2.5e6, 1e-3 (not 1.5e4)

통화 형식

통화 형식은 다양합니다. 미국($1,234.56), EU(1.234,56 €), 일본(¥1,234 소수 없음). 표시 서식에는 toLocaleString을 사용하세요. 파싱 전에는 통화 기호와 구분자를 제거한 뒤 parseFloat하세요. 정규식은 형식을 검증하고, 운영 환경 통화 서식에는 Intl.NumberFormat을 사용하세요.

regex
# US currency: $123.45 or $1,234.56
^\$\d{1,3}(?:,\d{3})*\.\d{2}$

# Optional $ and cents
^\$?\d{1,3}(?:,\d{3})*(?:\.\d{2})?$

# Optional sign for negative
^[+-]?\$?\d{1,3}(?:,\d{3})*(?:\.\d{2})?$

# Allow negative after $: -$5.00 or $-5.00
^[+-]?\$[+-]?\d+(?:\.\d{2})?$

# European format: 1.234,56 €
^\d{1,3}(?:\.\d{3})*,\d{2}\s?€$

# JavaScript
const usd = /^\$\d{1,3}(?:,\d{3})*\.\d{2}$/;
usd.test("$1,234.56")   # true
usd.test("$123.45")     # true
usd.test("$1234.56")    # false (needs comma)
usd.test("$1.234")      # false (needs 2 decimals)

# Loose: just match dollar amount
/\$[\d,.]+/g

# Extract all currency from text
"Total: $1,234.56, tax: $99.99".match(/\$[\d,]+\.\d{2}/g)
// ["$1,234.56", "$99.99"]

# Parse to number
const parseUSD = (s) => parseFloat(s.replace(/[$,]/g, ""));
parseUSD("$1,234.56")  # 1234.56

# Format number as currency
(1234.56).toLocaleString("en-US", { style: "currency", currency: "USD" })
// "$1,234.56"

# Python
import re
re.match(r"^\$\d{1,3}(?:,\d{3})*\.\d{2}$", "$1,234.56")

# Bitcoin: 0.5 BTC, satoshis
^\d+(?:\.\d{1,8})?\s?(?:BTC|sat|sats)$
14

문자열 교체

단순 교체

첫 번째만 교체할지 전체를 교체할지는 언어마다 다릅니다. JS replace()는 /g 없으면 첫 번째만, Python re.sub는 기본 전체(count=1이면 첫 번째), Java는 replaceFirst(첫 번째), replaceAll(정규식 전체), replace(리터럴 전체)입니다. 패턴 매칭에는 정규식을, 고정 텍스트 교체에는 리터럴 문자열 교체를 사용하세요.

regex
# Replace first occurrence

# JavaScript
"hello world".replace(/world/, "there")  # "hello there"
"hello world".replace(/o/, "0")          # "hell0 world" (first only)

# Python
import re
re.sub(r"world", "there", "hello world")  # "hello there"
re.sub(r"o", "0", "hello world", count=1)  # "hell0 world" (first only)

# Java
"hello world".replaceFirst("o", "0")    # "hell0 world"
"hello world".replace("world", "there") # literal, ALL occurrences

# PHP
preg_replace('/world/', 'there', 'hello world', 1)  # limit 1

# Replace literal string (no regex)
"hello.world".replace(".", " ")          # "hello world" (JS, literal)
"hello.world".replaceAll(".", " ")       # "hello world" (JS, literal)
# Python: str.replace is literal
"hello.world".replace(".", " ")          # "hello world"

# Replace using regex with special chars
"1.5".replace(/\./g, ",")               # "1,5" (escape dot)
"1+2=3".replace(/\+/g, "-")             # "1-2=3" (escape +)

# Chain replacements
"  Hello World  ".trim().replace(/\s+/g, "_").toLowerCase()
# "hello_world"

# Python chain
"_".join("  Hello World  ".strip().split()).lower()
# "hello_world"

모두 교체

전체 교체 동작: JS는 정규식에 /g가 필요하거나 문자열에 replaceAll을 사용합니다. Python의 re.sub와 str.replace는 기본적으로 전체를 바꿉니다. Java의 replaceAll(정규식)과 replace(리터럴)는 모두 전체를 바꿉니다. PHP preg_replace도 전체를 바꿉니다. 제한하려면 count(Python)나 $limit(PHP)를 사용하세요.

regex
# Replace ALL occurrences

# JavaScript: requires /g flag
"a-b-c-d".replace(/-/g, "+")          # "a+b+c+d"
"a-b-c-d".split("-").join("+")        # "a+b+c+d" (alternative)

# JavaScript: replaceAll (ES2021+)
"a-b-c-d".replaceAll("-", "+")        # "a+b+c+d" (string, not regex)
"a-b-c-d".replaceAll(/-/g, "+")       # needs /g flag with regex

# Python: re.sub does all by default
import re
re.sub(r"-", "+", "a-b-c-d")          # "a+b+c+d"

# Python: str.replace also does all
"a-b-c-d".replace("-", "+")           # "a+b+c+d" (literal)

# Java
"a-b-c-d".replaceAll("-", "+")        # regex, all
"a-b-c-d".replace("-", "+")           # literal, all

# PHP
preg_replace('/-/', '+', 'a-b-c-d')   # all

# Go
regexp.MustCompile("-").ReplaceAllString("a-b-c-d", "+")  # "a+b+c+d"

# Count occurrences
const count = (s, re) => (s.match(re) || []).length;
count("a-b-c-d", /-/g)  # 3

# Replace with limit (Python, PHP)
re.sub(r"-", "+", "a-b-c-d", count=2)      # "a+b+c-d"
preg_replace('/-/', '+', 'a-b-c-d', 2)     # "a+b+c-d"

# Global case-insensitive replace
"Hello hello HELLO".replace(/hello/gi, "hi")  # "hi hi hi"

교체에서 캡처 그룹

교체에서 캡처 그룹 참조: JS/Java는 $1, $2(전체 매치는 $&), Python은 \1, \2 또는 \g<1>(권장, \10 이상과의 모호성 회피), PHP는 $1 또는 \1을 허용합니다. 전체 매치는 $&(JS) / $0(Java) / \g<0>(Python)입니다. JS에서 리터럴 $는 $$로 이스케이프하세요.

regex
# Use captured groups in replacement

# Swap two words
"hello world".replace(/^(\w+) (\w+)$/, "$2 $1")  # "world hello"

# Reformat date
"2024-01-15".replace(/(\d{4})-(\d{2})-(\d{2})/, "$3/$2/$1")
# "15/01/2024"

# Wrap matches
"hello".replace(/\w+/g, "[$&]")  # "[hello]"
"hello world".replace(/\w+/g, "[$&]")  # "[hello] [world]"

# Duplicate matches
"abc".replace(/(\w)/g, "$1$1")  # "aabbcc"

# Conditional-like behavior with alternation
"Mr Smith".replace(/(Mr|Ms|Mrs) (\w+)/, "$2, $1.")
# "Smith, Mr."

# Python: \1, \2 or \g<1>, \g<2> (preferred)
import re
re.sub(r"(\d{4})-(\d{2})-(\d{2})", r"\3/\2/\1", "2024-01-15")
# "15/01/2024"

re.sub(r"(\w+)", r"[\1]", "hello")  # "[hello]"

# Use named groups
"2024-01-15".replace(
  /(?<y>\d{4})-(?<m>\d{2})-(?<d>\d{2})/,
  "$<d>/$<m>/$<y>"
)  # "15/01/2024"

# Python named
re.sub(
  r"(?P<y>\d{4})-(?P<m>\d{2})-(?P<d>\d{2})",
  r"\g<d>/\g<m>/\g<y>",
  "2024-01-15"
)

# Reference whole match: $& (JS), $0 (Java), \g<0> (Python)
"abc".replace(/\w/g, "[$&]")  # "[a][b][c]"
re.sub(r"\w", r"[\g<0>]", "abc")  # "[a][b][c]"

# Literal $ in replacement (JS): use $$
"price".replace(/price/, "$$100")  # "$100"

대소문자 변환

정규식 + 함수 교체로 대소문자를 변환합니다. 타이틀 케이스(각 단어 첫 글자 대문자), camelCase↔snake_case↔kebab-case 변환은 캡처 그룹과 toUpperCase/toLowerCase를 사용합니다. Python은 람다 함수로 같은 효과를 냅니다. 교체 전에 캡처한 ([A-Z]) 패턴이 케이스 스타일 변환의 핵심입니다.

regex
# Capitalize first letter of each word (title case)
"hello world".replace(/\b\w/g, c => c.toUpperCase())
# "Hello World"

# Capitalize first letter of string only
"hello world".replace(/^\w/, c => c.toUpperCase())
# "Hello world"

# Lowercase first letter, rest unchanged
"HelloWorld".replace(/^\w/, c => c.toLowerCase())
# "helloWorld"

# camelCase to snake_case
"myVariableName".replace(/([A-Z])/g, "_$1").toLowerCase()
# "my_variable_name"

# snake_case to camelCase
"my_variable_name".replace(/_([a-z])/g, (_, c) => c.toUpperCase())
# "myVariableName"

# kebab-case to camelCase
"my-variable-name".replace(/-([a-z])/g, (_, c) => c.toUpperCase())
# "myVariableName"

# camelCase to kebab-case
"myVariableName".replace(/([A-Z])/g, "-$1").toLowerCase()
# "my-variable-name"

# UPPER_CASE to lowerCase
"MY_VAR_NAME".replace(/_/g, "").toLowerCase()
# "myvarname" (without proper conversion)

# Constant case to camelCase
"MY_VAR_NAME".toLowerCase().replace(/_([a-z])/g, (_, c) => c.toUpperCase())
# "myVarName"

# Sentence case: capitalize first letter of each sentence
"hello. world. foo.".replace(/(^|\.\s+)([a-z])/g, (_, p, c) => p + c.toUpperCase())
# "Hello. World. Foo."

# Python equivalents
import re
re.sub(r"\b\w", lambda m: m.group().upper(), "hello world")
# "Hello World"

re.sub(r"([A-Z])", r"_\1", "myVar").lower()
# "my_var"

다듬기와 정리

흔한 정리 작업: 다듬기(JS는 내장 .trim(), Python은 .strip()이 더 빠름), 여러 공백 축소(\s+ -> 공백 하나), 줄바꿈 정규화(CRLF/CR -> LF), 주석 제거. 각 줄의 끝 공백 제거처럼 줄 단위 작업에는 여러 줄 플래그(/m)를 사용하세요.

regex
# Trim leading and trailing whitespace
"  hi  ".replace(/^\s+|\s+$/g, "")  # "hi"
# Note: JS String.prototype.trim() is preferred: "  hi  ".trim()

# Trim leading only
"  hi  ".replace(/^\s+/, "")  # "hi  "
# Or: "  hi  ".replace(/^\s+/g, "")

# Trim trailing only
"  hi  ".replace(/\s+$/, "")  # "  hi"

# Collapse multiple spaces into one
"a   b    c".replace(/\s+/g, " ")  # "a b c"

# Collapse but preserve newlines
"a   b

  c".replace(/[ \t]+/g, " ").replace(/\n{2,}/g, "\n")
# "a b
c"

# Remove all whitespace
"a b c".replace(/\s/g, "")  # "abc"
"a b c".replace(/\s+/g, "")  # "abc"

# Remove blank lines
"text\n\n\nmore".replace(/^\s*$(?:\n|$)/gm, "")
# "text
more"

# Normalize line endings
"text\r\nmore".replace(/\r\n/g, "\n")  # CRLF -> LF
"text\rmore".replace(/\r/g, "\n")        # CR -> LF

# Remove trailing whitespace from each line
"text  \nmore ".replace(/\s+$/gm, "")
# "text
more"

# Strip comments (/* */ and //)
code.replace(/\/\*[\s\S]*?\*\//g, "")  # block comments
code.replace(/\/\/.*$/gm, "")              # line comments

# Python equivalents
import re
re.sub(r"^\s+|\s+$", "", "  hi  ")  # "hi"
re.sub(r"\s+", " ", "a   b    c")    # "a b c"
re.sub(r"\s+$", "", "a   ", flags=re.M)  # trim trailing per line

HTML 태그 제거

HTML 태그는 /<[^>]+>/g로 제거합니다(단순하지만 간단한 경우에는 동작). <script>/<style>은 내용과 함께 최소 일치 [\s\S]*?로 제거하세요. 실제 HTML에는 파서(JS는 DOM, Python은 BeautifulSoup)를 사용하세요. 정규식은 중첩 태그, 속성의 >, 잘못된 HTML에서 실패합니다. 엔티티는 DOM이나 html.unescape(Python)로 디코드하세요.

regex
# Naive: remove anything between < and >
"<p>Hello</p>".replace(/<[^>]+>/g, "")  # "Hello"

# Strip all tags but keep content
"<div><p>Hello <b>world</b></p></div>".replace(/<[^>]+>/g, "")
# "Hello world"

# Remove specific tag
"<div>keep</div>".replace(/<\/?div>/g, "")  # "keep"

# Remove script and style blocks (with content)
html.replace(/<script[\s\S]*?<\/script>/gi, "")
html.replace(/<style[\s\S]*?<\/style>/gi, "")

# Decode basic HTML entities
"AT&amp;T".replace(/&amp;/g, "&")
"&lt;tag&gt;".replace(/&lt;/g, "<").replace(/&gt;/g, ">")
"&nbsp;".replace(/&nbsp;/g, " ")
"&quot;".replace(/&quot;/g, '\"')

# Decode all entities via DOM (JS)
function decodeEntities(s) {
  const t = document.createElement("textarea");
  t.innerHTML = s;
  return t.value;
}

# Remove attributes from tags
'<a href="x" class="y">link</a>'.replace(/(<\w+)[^>]*>/g, "$1>")
# "<a>link</a>" (but the </a> stays; need to handle closing too)

# Self-closing tags
html.replace(/<\w+[^>]*/>/g, "")

# Strip HTML comments
html.replace(/<!--[\s\S]*?-->/g, "")

# Python
import re
re.sub(r"<[^>]+>", "", "<p>Hello</p>")  # "Hello"
re.sub(r"<script[\s\S]*?</script>", "", html, flags=re.I)

# WARNING: regex is fragile for HTML parsing.
# Use DOMParser (JS) or BeautifulSoup (Python) for real HTML.
15

추출과 분할

첫 매치 추출

첫 매치 추출: JS String.match()는 배열(또는 null), Python re.search는 Match 객체(또는 None), Java Matcher.find()는 다음 매치로 이동, PHP preg_match는 배열에 그룹을 채웁니다. 패턴이 어디에나 있을 수 있으면 search(Python)를 사용하세요. match는 시작에 고정됩니다.

regex
# Extract first match

# JavaScript
const m = "price: $42.50, tax: $3.00".match(/\$(\d+\.\d{2})/);
// m[0] = "$42.50", m[1] = "42.50"
if (m) console.log(m[1]);  // "42.50"

# Python
import re
m = re.search(r"\$(\d+\.\d{2})", "price: $42.50, tax: $3.00")
if m:
    print(m.group(1))  # "42.50"

# Java
Matcher m = Pattern.compile("\\$(\\d+\\.\\d{2})")
                   .matcher("price: $42.50");
if (m.find()) { String price = m.group(1); }

# PHP
if (preg_match('/\$(\d+\.\d{2})/', 'price: $42.50', $m)) {
    echo $m[1];  // "42.50"
}

# Extract with named groups
const m2 = "2024-01-15".match(
  /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/
);
if (m2) console.log(m2.groups.year);  // "2024"

# Test if pattern exists (no extraction needed)
const has = /\d{4}-\d{2}-\d{2}/.test("date: 2024-01-15");  // true

# Python: search vs match vs fullmatch
re.search(r"abc", "xabcx")   # finds anywhere
re.match(r"abc", "abcx")     # anchored at start
re.fullmatch(r"abc", "abc")  # entire string

모든 매치 추출

모든 매치 추출: JS match()에 /g를 붙이면 매치의 평면 배열(그룹 정보 없음)을, matchAll(ES2020+)은 전체 정보가 담긴 반복자를 반환합니다. Python의 re.findall은 그룹 목록(그룹이 없으면 전체 매치)을 반환합니다. 큰 텍스트를 지연 반복하려면 re.finditer를 사용하세요.

regex
# Extract ALL matches

# JavaScript: with /g flag, match() returns array of matches (no groups)
"1a2b3c".match(/\d/g)        # ["1", "2", "3"]
"a1 b2 c3".match(/\d+/g)     # ["1", "2", "3"]

# matchAll (ES2020+) returns iterator with full match info
const matches = [..."2024-01-15 2025-02-20".matchAll(/(\d{4})-(\d{2})-(\d{2})/g)];
// matches[0][0]="2024-01-15", matches[0][1]="2024", ...

# Python: re.findall returns list of group(s)
import re
re.findall(r"\d+", "a1 b2 c3")            # ["1", "2", "3"]
re.findall(r"(\d+)-(\d+)", "12-34 56-78")  # [("12","34"), ("56","78")]
# Note: if groups present, returns tuples of groups, not whole match
# Use (?:...) or non-capturing to get whole match
re.findall(r"\d+-\d+", "12-34 56-78")    # ["12-34", "56-78"]

# re.finditer returns match objects (lazy iterator)
for m in re.finditer(r"\d+", "a1 b2 c3"):
    print(m.group(), m.start(), m.end())

# Java: Matcher.find() in loop
Matcher m = Pattern.compile("\\d+").matcher("a1 b2 c3");
while (m.find()) { System.out.println(m.group()); }

# PHP: preg_match_all fills multidimensional array
preg_match_all('/\d+/', 'a1 b2 c3', $m, PREG_SET_ORDER);
// $m[0][0] = "1", $m[1][0] = "2", ...

# Count matches
(len("a1 b2 c3".match(/\d/g) || []))  # 3 (JS)
len(re.findall(r"\d", "a1 b2 c3"))     # 3 (Python)

문자열 분할

정규식으로 문자열을 분할합니다. JS String.split(regex), Python re.split, Java String.split, PHP preg_split, Go regexp.Split. 패턴에 캡처 그룹이 있으면 구분자가 결과 배열에 남습니다. 분할 횟수를 제한하려면 limit/maxsplit을 사용하세요. 공백 분할: /\s+/는 여러 공백, 탭, 줄바꿈을 처리합니다.

regex
# Split string by pattern

# JavaScript
"a,b,c".split(",")            # ["a", "b", "c"]
"a, b , c".split(/\s*,\s*/)  # ["a", "b", "c"] (trim around comma)
"1-2-3".split("-")            # ["1", "2", "3"]

# Split with capture group keeps the delimiter
"a1b2c3".split(/(\d)/)       # ["a", "1", "b", "2", "c", "3", ""]

# Limit splits
"a,b,c,d".split(",", 2)       # ["a", "b"] (rest in last element)
"a,b,c,d".split(/,/, 2)       # ["a", "b"]

# Python
import re
re.split(r"\s*,\s*", "a, b , c")  # ["a", "b", "c"]
re.split(r"(\d)", "a1b2c3")         # ["a", "1", "b", "2", "c", "3", ""]
re.split(r",", "a,b,c", maxsplit=1)  # ["a", "b,c"]

# Java
"a,b,c".split(",")            # ["a", "b", "c"]
"a, b , c".split("\\s*,\\s*")  # ["a", "b", "c"]
"a,b,c,d".split(",", 2)       # ["a", "b,c,d"]

# PHP
preg_split('/\s*,\s*/', 'a, b , c')  # ["a", "b", "c"]
preg_split('/(\d)/', 'a1b2c3', -1, PREG_SPLIT_DELIM_CAPTURE)

# Go
regexp.MustCompile("\\s*,\\s*").Split("a, b , c", -1)

# Split on whitespace (any)
"a   b\tc\nd".split(/\s+/)  # ["a", "b", "c", "d"]

# Split lines
"line1\nline2\r\nline3".split(/\r\n|\r|\n/)  # ["line1", "line2", "line3"]

키-값 쌍 추출

(\w+)\s*[=:]\s*([^,;\n]+) 같은 패턴으로 key=value 쌍을 추출합니다. Object.fromEntries + matchAll(JS) 또는 dict + findall(Python)로 깔끔한 객체를 만드세요. 실제 URL 쿼리 문자열과 HTTP 헤더에는 내장 URL/URLSearchParams(JS)나 urllib.parse(Python)를 권장합니다. URL 인코딩을 올바르게 처리합니다.

regex
# Extract key=value pairs

# Match key=value (or key: value)
(\w+)\s*[=:]\s*([^,;\n]+)

# JavaScript
const text = "name=Alice, age=30; city: NYC";
const pairs = [...text.matchAll(/(\w+)\s*[=:]\s*([^,;\n]+)/g)];
const obj = Object.fromEntries(pairs.map(m => [m[1], m[2].trim()]));
// { name: "Alice", age: "30", city: "NYC" }

# Python
import re
text = "name=Alice, age=30; city: NYC"
pairs = re.findall(r"(\w+)\s*[=:]\s*([^,;\n]+)", text)
dict(pairs)  # {"name": "Alice", "age": "30", "city": "NYC"}

# URL query string parsing
"?a=1&b=2&c=3".match(/[?&]([^=]+)=([^&]+)/g)
// ["?a=1", "&b=2", "&c=3"]

# Parse query string into object
const qs = "a=1&b=2&c=hello%20world";
const params = Object.fromEntries(
  [...qs.matchAll(/([^=&]+)=([^&]*)/g)]
    .map(m => [m[1], decodeURIComponent(m[2])])
);
// { a: "1", b: "2", c: "hello world" }

# Python equivalent
from urllib.parse import parse_qs
parse_qs("a=1&b=2&c=hello%20world")
# {"a": ["1"], "b": ["2"], "c": ["hello world"]}

# HTTP header parsing
const headers = "Content-Type: text/html\nAccept: */*";
const headerObj = Object.fromEntries(
  [...headers.matchAll(/^(\w[\w-]*):\s*(.+)$/gm)]
    .map(m => [m[1], m[2]])
);
// { "Content-Type": "text/html", "Accept": "*/*" }

토큰화

토큰화는 텍스트를 의미 단위(단어 \w+, 숫자, 문자열, 연산자, 구두점)로 나눕니다. 토크나이저 패턴에는 캡처 그룹이 있는 선택을 사용하세요. Python의 re.finditer는 위치가 담긴 매치 객체를 제공합니다. 실제 NLP 토큰화에는 NLTK나 spaCy 같은 라이브러리를 사용하세요. 정규식이 처리 못 하는 경계 사례를 다룹니다.

regex
# Tokenize: split text into tokens (words, numbers, punctuation)

# Simple word tokenization
\w+              # sequences of word chars
"Hello, world! 42".match(/\w+/g)  # ["Hello", "world", "42"]

# Tokenize keeping punctuation
/[A-Za-z0-9]+|[^\sA-Za-z0-9]/g
"Hello, world!".match(/[A-Za-z0-9]+|[^\sA-Za-z0-9]/g)
# ["Hello", ",", "world", "!"]

# Number tokens
/\d+\.?\d*|\.[0-9]+/
"Price 3.14 and .5".match(/\d+\.?\d*|\.[0-9]+/g)  # ["3.14", ".5"]

# String literals
/"([^"\\]|\\.)*"|'([^'\\]|\\.)*'/

# Programming language tokens (simplified)
const tokens = source.matchAll(
  /(?<comment>\/\/.*$|\/\*[\s\S]*?\*\/)
   |(?<string>"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')
   |(?<number>\d+\.?\d*)
   |(?<ident>[A-Za-z_]\w*)
   |(?<op>[+\-*/=<>!&|]+)
   |(?<punct>[(){}[\];,.])/gx
);

# Split into words preserving position
import re
for m in re.finditer(r"\w+", "Hello world foo"):
    print(m.group(), m.start(), m.end())

# Sentence tokenization (simplified)
text.split(/(?<=[.!?])\s+/)
# Splits on whitespace after . ! or ?

# Whitespace tokenization (preserves tokens)
text.split(/(\s+)/)  # keeps whitespace as separate elements
16

탐욕적 vs 최소 일치

탐욕적 기본값

탐욕적 수량자는 최대한 많이 일치한 뒤 나머지 패턴이 성공하도록 역추적합니다. 이 때문에 HTML에서 <.+>가 <b>...</b><i>...</i> 전체를 하나로 일치시키는 예상 밖 결과가 자주 생깁니다. 최소 일치 수량자나 구체적 문자 클래스로 피하세요.

regex
# Quantifiers are GREEDY by default - match as much as possible
# * + ? {n,m} all greedy

# Greedy: .* takes everything, then backtracks
"<a> <b> <c>".match(/<.*>/)   # ["<a> <b> <c>"] (whole thing!)

# Greedy backtracking example
"12345".match(/\d+\d/)   # \d+ takes "1234", last \d takes "5"

# Greedy with anchored end - takes everything then backtracks to find end
"hello world end".match(/^.*(end).*$/)  # captures "end"

# Common greedy patterns
.*            # entire line (zero or more)
.+            # entire line (one or more)
\d+           # all consecutive digits
\w+           # all consecutive word chars
\s+           # all consecutive whitespace

# HTML gotcha: greedy matches too much
"<b>bold</b> and <i>italic</i>".match(/<.+>/)
# ["<b>bold</b> and <i>italic</i>"] - WRONG, matches across tags!

# Greedy on alternation
"cat or dog".match(/cat|cat dog/)  # ["cat"] - first alternative wins

# Email greedy
"a@b@c".match(/.+@.+/)  # ["a@b@c"] - greedy .+ takes "a@b"

최소 일치 수량자

최소 일치 수량자(*? +? ??)는 최소한으로 일치합니다. 구분자 사이의 가장 짧은 매치를 찾을 때 사용하세요. HTML 태그는 <.*?>, 따옴표 문자열은 ".*?"입니다. 단순한 따옴표 문자열에는 '.*?'보다 '[^']*'가 보통 더 빠르고 명확합니다.

regex
# Add ? after a quantifier to make it LAZY (non-greedy)
# Lazy: match as LITTLE as possible, expand only if needed

# Lazy quantifiers
*?     # lazy zero or more
+?     # lazy one or more
??     # lazy zero or one
{n,m}? # lazy range

# Lazy: stops at FIRST closing tag
"<a> <b> <c>".match(/<.*?>/)   # ["<a>"] - just the first tag
"<b>bold</b> <i>italic</i>".match(/<.+?>/)
# ["<b>"] - just the first opening tag

# Find quoted strings
'"a" and "b"'.match(/".*?"/g)   # ['"a"', '"b"']
'"a" and "b"'.match(/".*"/g)    # ['"a" and "b"'] (greedy wrong!)

# Capture content between tags
"<div>hello</div>".match(/<div>(.*?)<\/div>/)  # captures "hello"

# Lazy vs negated class (often faster alternative)
# These are equivalent but negated class is usually faster:
'"hello"'.match(/"[^"]*"/)     # uses negated class - preferred
'"hello"'.match(/".*?"/)       # uses lazy - works but slower

# Multiple lazy quantifiers
'(.*?)(.*?)(.*?)'  # all lazy, but each expands as needed

# When greedy fails, lazy often helps
# Match XML comments <!-- ... -->
text.match(/<!--[\s\S]*?-->/g)  # lazy: stops at first -->

흔한 최소 일치 패턴

흔한 최소 일치 패턴: 태그 내용(<tag>(.*?)</tag>), 따옴표 문자열('[^']*'), 괄호 내용, 주석. 구분된 내용에는 최소 일치 수량자(.*?)보다 부정 문자 클래스([^']*)를 권장합니다. 더 명확하고 대개 더 빠릅니다. 구분자가 여러 문자일 때 최소 일치가 특히 빛납니다.

regex
# Most common lazy patterns

# Content between tags (HTML/XML)
<([a-z][a-z0-9]*)\b[^>]*>(.*?)<\/\1>
# captures tag name and inner content (lazy)

# Quoted strings
"([^"]*)"        # double-quoted (preferred over ".*?")
'([^']*)'        # single-quoted

# Bracketed content
\[([^\]]*)\]   # content inside [ ]
\(([^()]*)\)   # content inside ( )
\{([^{}]*)\}   # content inside { }

# Comments
/\*[\s\S]*?\*/   # C-style block comment
<!--.*?-->        # HTML comment (with /s for multiline)

# URL in text
https?://\S+?["'\s<>]   # URL until delimiter

# Path components
/([^/]+)         # one path segment

# Code block in markdown
\`\`\`([\s\S]*?)\`\`\`   # fenced code block

# Lazy with anchors for validation
^.*?\bword\b.*$  # line containing "word" (lazy doesn't matter here)

# Variable assignment
(\w+)\s*=\s*("[^"]*"|'[^']*'|\d+)

언제 무엇을 쓸까

가장 긴 매치(마지막 구분자까지)나 끝이 고유한 경우에는 탐욕적을 선택하세요. 구분자가 여러 개이거나 각 매치를 따로 얻고 싶으면 최소 일치를 선택하세요. 가장 좋은 방법은 구체적 문자 클래스([^"/]*)로 문제를 아예 피하는 것입니다. 보통 최소 일치 수량자보다 명확하고 빠릅니다.

regex
# Use GREEDY when:
# - You want the longest possible match
# - The end is uniquely identified
# - You want to capture until the LAST occurrence

# Capture everything to the last occurrence of X
^.*X         # greedy: matches up to the LAST X
"everything;until;last;semicolon".match(/^.*;/)  # "everything;until;last;"

# Use LAZY when:
# - You want the shortest match
# - Multiple delimiters exist
# - You want to match each occurrence separately

# Match each quoted string
'"a","b","c"'.match(/"[^"]*"/g)   # ['"a"', '"b"', '"c"'] - non-lazy, negated
'"a","b","c"'.match(/".*?"/g)     # same result with lazy

# When neither works well: use specific character classes
# Match content of <div> (allowing nested non-div tags)
<div\b[^>]*>((?:(?!<div\b)[\s\S])*)<\/div>

# Practical: extract first URL from text
const text = 'visit https://example.com or https://other.com';
const m = text.match(/https?:\/\/[^\s<>"]+/i);
// m[0] = "https://example.com" (greedy on char class, stops at space)

# Use anchored patterns to avoid greediness issues
^.*?word.*$    # lazy doesn't help here - anchored greedy works fine

# Performance: greedy can be FASTER when no backtracking needed
\d+           # greedy but no backtrack issue (concrete chars)
.*?word        # lazy to avoid grabbing too much

치명적 역추적

치명적 역추적: 겹치는 선택지가 있는 중첩 수량자((a+)+ 등)는 일치하지 않는 입력에서 지수 시간을 유발합니다. 원자 그룹(?>...), 소유 수량자(a++), 겹침을 피하는 리팩터링, 타임아웃(Python 3.11+), 또는 선형 시간이지만 역참조를 지원하지 않는 RE2(Go 엔진) 사용으로 해결하세요.

regex
# Catastrophic backtracking: exponential time on certain inputs
# Caused by nested quantifiers with overlapping alternatives

# DANGEROUS: (a+)+ on "aaaaaaaaaaaaaaaaaaaaaaa!"
(a+)+         # nested quantifier - exponential backtracking on no-match

# DANGEROUS: overlapping alternatives
(a|a)*b       # tries many combinations before failing

# DANGEROUS: classic email regex
([a-zA-Z0-9._%+-]+@([a-zA-Z0-9.-]+\.)+[a-zA-Z]{2,})+
# nested + with alternation can blow up

# How to detect: test with long inputs that DON'T match
# If it hangs on "aaaaaaa...!" - you have it

# Fixes:
# 1. Use atomic groups (PCRE, Java, .NET - NOT JS)
(?>a+)+       # atomic group - no backtracking into group

# 2. Use possessive quantifiers (Java, PCRE - NOT JS)
a++           # possessive - no backtracking

# 3. Refactor: avoid overlapping alternatives
# Bad:  (a|a)*b
# Good: a*b

# 4. Be specific with character classes
# Bad:  (.*)*
# Good: [a-z]*  (or whatever specific chars)

# 5. Use unrolling the loop technique
# Replace (?:a*b*)+ with a*(?:ba*b)*  (for example)

# 6. Set a timeout (Python 3.11+)
import re
re.compile(r"(a+)+").match("a" * 30 + "b", timeout=1.0)

# 7. Use RE2 (linear-time engine) in Go, or Google's re2 library
# RE2 doesn't support backreferences but is immune to this issue

# Test your regex at regex101.com - it warns about catastrophic patterns
17

역참조

번호 역참조

역참조(\1, \2)는 앞서 캡처한 것과 같은 텍스트와 일치합니다. 고전적 용도: 반복 단어(\b(\w+)\s+\1\b), HTML 태그 쌍(<([a-z]+)>...</\1>), 짝 따옴표, 일관된 날짜 구분자. 역참조는 그룹이 캡처한 내용과 정확히 일치해야 하며, 패턴을 다시 일치시키는 것이 아닙니다.

regex
# \1, \2, ... refer to a PREVIOUSLY captured group's match
# The backreference must match the SAME text the group captured

# Find repeated word
\b(\w+)\s+\1\b
# Matches: "hello hello", "the the", "is is"

# Match HTML/XML tag pairs
<([a-z][a-z0-9]*)\b[^>]*>[\s\S]*?</\1>
# <div>...</div>, <p>...</p>, <span class="x">...</span>

# Match paired quotes (single or double)
(["\'])([^\1]*?)\1
# "hello" or 'hello' - same opening and closing quote

# Date with consistent separator
(\d{4})([-/])(\d{2})\2(\d{2})
# 2024-01-15 OK (same -)
# 2024-01/15 REJECTED (different separators)

# Palindrome-ish: abba
(\w)(\w)\2\1

# JavaScript
"hello hello world".match(/\b(\w+)\s+\1\b/)  # ["hello hello", "hello"]
"<div>x</div>".match(/<([a-z]+)>([\s\S]*?)<\/\1>/)  # ["<div>x</div>", "div", "x"]

# Python
import re
re.search(r"\b(\w+)\s+\1\b", "hello hello")  # match
re.search(r"<([a-z]+)>[\s\S]*?</\1>", "<b>x</b>")  # match

# Backreferences in replacement (different from in-pattern backrefs)
"hello".replace(/(\w)/g, "$1$1")  # "hheelllloo"

명명 역참조

명명 역참조는 패턴을 자기 문서화하게 만듭니다. JS/.NET/Java는 \k<name>, Python/PCRE는 (?P=name)을 사용합니다. 명명 그룹(?<name>...)과 결합해 태그 쌍, 짝 구분자, 반복 단어 탐지에 쓰세요. 교체에서 명명 역참조는 $<name>(JS) 또는 \g<name>(Python)입니다.

regex
# Named capture group + named backreference

# JavaScript: (?<name>...) then \k<name>
(?<word>\w+)\s+\k<word>
(?<tag>[a-z]+)>[\s\S]*?</\k<tag>>

# Python: (?P<name>...) then (?P=name)
(?P<word>\w+)\s+(?P=word)
(?P<tag>[a-z]+)>[\s\S]*?</(?P=tag)>

# .NET: (?<name>...) then \k<name> (same as JS)
# Java: (?<name>...) then \k<name>
# PHP/PCRE: (?P<name>...) then (?P=name) or \k<name>

# JavaScript example
const re = /\b(?<word>\w+)\s+\k<word>\b/;
"the the cat".match(re)  # ["the the", "the"]

# Python example
import re
re.search(r"(?P<word>\w+)\s+(?P=word)", "hello hello")  # match

# Practical: match HTML with named groups
const html = '<div class="x"><span>hi</span></div>';
const re2 = /<(?<tag>[a-z][a-z0-9]*)\b[^>]*>(?<content>[\s\S]*?)<\/\k<tag>>/;
const m = html.match(re2);
// m.groups.tag = "div", m.groups.content = '<span>hi</span>'

# Quote matching with named group
const quoteRe = /(?<q>["\'])[^\k<q>]*\k<q>/g;
'text "hello" and \'world\''.match(quoteRe)  # ['"hello"', "\'world\'"]

# Named backref in replacement (JS)
"hello hello".replace(/(?<w>\w+)\s+\k<w>/, "$<w>")  # "hello"

반복 단어

반복 단어 탐지: \b(\w+)\s+\1\b는 'the the'처럼 두 번 나온 단어를 찾습니다. 대소문자 무시에는 /i를 사용하세요. $1(JS) 또는 \1(Python)로 교체해 수정합니다. 변형: 세 번 반복은 (\s+\1){2}, 흔한 단어만, 'had had' 같은 정상 중복은 부정 전방 탐색으로 제외합니다.

regex
# Find repeated (doubled) words: "the the", "is is"
\b(\w+)\s+\1\b

# Case-insensitive
/\b(\w+)\s+\1\b/i

# JavaScript
const dupRe = /\b(\w+)\s+\1\b/gi;
"I went to the the store and and bought milk".match(dupRe)
# ["the the", "and and"]

# Python
import re
re.findall(r"\b(\w+)\s+\1\b", "the the cat", re.IGNORECASE)
# ["the"]

# Fix doubled words (replace with single)
"I went to the the store".replace(/\b(\w+)\s+\1\b/gi, "$1")
# "I went to the store"

# Python
re.sub(r"\b(\w+)\s+\1\b", r"\1", "the the cat", flags=re.I)
# "the cat"

# Find triple repeats
\b(\w+)(\s+\1){2}\b  # "blah blah blah"

# Find any consecutive repeats
\b(\w+)(?:\s+\1)+\b  # "blah blah blah blah"

# Limit to specific words
\b(the|and|or|is)\s+\1\b  # only common stop words

# Find non-trivial repeats (3+ letters)
\b(\w{3,})\s+\1\b  # excludes short words like "is is"

# Skip common valid doubles (very rare in English)
# "had had", "that that" - use negative lookahead to exclude
\b(?!had|that)(\w+)\s+\1\b

HTML 태그 매칭

<([a-z][a-z0-9]*)\b[^>]*>[\s\S]*?</\1>로 HTML 태그 쌍을 일치시킵니다. 태그 이름을 캡처하고 역참조로 닫는 태그가 같은지 보장합니다. 경고: 정규식은 같은 이름의 중첩 태그(<div><div>x</div></div>)를 처리할 수 없습니다. 중첩 HTML에는 실제 파서(JS는 DOM, Python은 BeautifulSoup)를 사용하세요.

regex
# Match opening and closing tag with backreference
<([a-z][a-z0-9]*)\b[^>]*>[\s\S]*?</\1>
# <div>...</div>, <span class="x">...</span>

# JavaScript
const html = '<div class="x"><p>hello</p></div>';
const re = /<([a-z][a-z0-9]*)\b[^>]*>([\s\S]*?)<\/\1>/gi;
const m = html.match(re);
// ["<div class="x"><p>hello</p></div>"]

# Iterate over all top-level tags
const re2 = /<([a-z][a-z0-9]*)\b[^>]*>([\s\S]*?)<\/\1>/gi;
let m2;
while ((m2 = re2.exec(html)) !== null) {
  console.log(m2[1], m2[2]);
}

# Python
import re
re.findall(r"<([a-z][a-z0-9]*)\b[^>]*>([\s\S]*?)</\1>",
           html, re.IGNORECASE)
# [("div", "<p>hello</p>")]

# Self-closing tags
<([a-z][a-z0-9]*)\b[^>]*/>

# Both opening and self-closing
<([a-z][a-z0-9]*)\b[^>]*(?:/>|>[\s\S]*?</\1>)

# Specific tag
<div\b[^>]*>([\s\S]*?)</div>

# WARNING: backreferences can't handle nested same-name tags
# <div><div>x</div></div> - regex can't match outer properly
# Use a parser for nested HTML

# Attribute extraction
<(?<tag>[a-z]+)(?<attrs>[^>]*)>(?<content>[\s\S]*?)</\k<tag>>

따옴표 매칭

(['\"])([^\1]*?)\1로 일관된 구분자를 가진 따옴표 문자열을 일치시킵니다. 여는 따옴표를 캡처하고 같은 문자로 닫히도록 요구합니다. 이스케이프된 따옴표가 있는 문자열("hello \"world\"")에는 더 복잡한 (['\"])(?:\\.|(?!\1)[^\\])*\1을 사용하세요. 단순한 패턴은 이스케이프된 따옴표에서 깨집니다.

regex
# Match a quoted string with CONSISTENT quote char
(["\'])([^\1]*?)\1
# "hello" or 'hello' - opening quote remembered, closing must match

# JavaScript
const str = 'She said "hello" and he said \'hi\'';
const re = /(["\'])([^"\']*?)\1/g;
str.match(re)  # ['"hello"', "\'hi\'"]

# With named group (clearer)
const re2 = /(?<q>["\'])(?<content>[^\k<q>]*?)\k<q>/g;

# Handle escaped quotes inside
# Allow \" inside double quotes, \' inside single
(["\'])(?:\\.|(?!\1)[^\\])*\1
# "hello \"world\"" matches correctly

# Python
import re
re.findall(r'(["\'])([^\1]*?)\1', 'She said "hello"')
# [('"', 'hello')]

# Practical: extract all quoted strings
text.match(/(["\'])(?:(?!\1).)*\1/g)

# Triple-quoted strings (Python-like)
(?<="""|''')[\s\S]*?\1

# Backtick strings (JS template literals)
`(?:[^\`\\]|\\.)*`

# Replace quoted content
'"hello world"'.replace(/"([^"]*)"/, "[$1]")  # "[hello world]"

# WARNING: this naive pattern fails on escaped quotes:
# "hello \"world\"" - the \" ends the match early
# Use the escape-aware version above for production
18

유니코드 정규식

유니코드 모드

유니코드 모드는 비ASCII 텍스트에 필수입니다. JS는 /u 플래그(ES6+), Python 3는 기본 유니코드(re.ASCII로 제한), PHP는 /u, Java는 Pattern.UNICODE_CHARACTER_CLASS를 사용합니다. JS에서 /u가 없으면 서로게이트 쌍(이모지, CJK)이 잘못 처리되어 수량자와 앵커가 이를 하나가 아닌 두 코드 단위로 취급합니다.

regex
# JavaScript: /u flag for Unicode mode (ES6+)
/^.$/u.test("𝌆")    # true (one code point)
/^.$/.test("𝌆")     # false (two UTF-16 code units without /u)

# Without /u: surrogate pairs broken
"𝌆".length          # 2 (surrogate pair)
/[\uD834\uDF06]/u.test("𝌆")  # true (with /u, treats as one code point)

# Python 3: Unicode is default
import re
re.search(r"\w+", "日本語")  # matches (Unicode by default)
# re.ASCII or re.A for ASCII-only
re.search(r"\w+", "日本語", re.ASCII)  # ASCII-only, no match

# PHP: /u flag for UTF-8 mode
preg_match('/^.$/u', '𝌆')  # 1 (match, treats as one code point)

# Java: Pattern.UNICODE_CHARACTER_CLASS
Pattern p = Pattern.compile("\\w+", Pattern.UNICODE_CHARACTER_CLASS);

# .NET: Unicode by default
# Go (RE2): Unicode by default

# IMPORTANT: /u changes quantifier behavior in JS
/[😂]{2}/u.test("😂😂")  # true (quantifier on code point)
/[😂]{2}/.test("😂😂")   # unpredictable (code units)

# Case-insensitive Unicode (with /iu)
/\w/iu.test("Ω")  # true (Σ/σ/ς equivalence)

# Validate astral plane characters (emoji, ancient scripts)
/^[\u{1F300}-\u{1F9FF}]+$/u  # emoji range
/[\u{1F600}-\u{1F64F}]/u     # emoticons

속성 이스케이프 \p{...}

유니코드 속성 이스케이프(\p{L}, \p{N}, \p{Script=Han}, \p{Emoji})는 코드 포인트 범위가 아니라 문자 속성으로 일치합니다. [\u4e00-\u9fff] 같은 범위보다 훨씬 읽기 쉽고 견고합니다. JS는 /u 플래그가 필요하고(속성은 ES2018+), Python은 서드파티 'regex' 모듈이나 Python 3.13+가 필요합니다. PHP/Java/.NET/Go는 기본 지원합니다.

regex
# Unicode property escapes (require /u in JS)

# \p{L} or \p{Letter} - any letter (any script)
/^\p{L}+$/u.test("Hello")       # true
/^\p{L}+$/u.test("日本語")       # true (CJK letters)
/^\p{L}+$/u.test("Привет")      # true (Cyrillic)

# \p{N} or \p{Number} - any number
/^\p{N}+$/u.test("123")         # true
/^\p{N}+$/u.test("١٢٣")         # true (Arabic-Indic digits)

# \p{P} or \p{Punctuation}
/^\p{P}+$/u.test("!?.")         # true

# \p{S} or \p{Symbol}
/^\p{S}+$/u.test("$€¥")         # true (currency symbols)

# \p{Z} or \p{Separator} (whitespace including Unicode)
/^\p{Z}+$/u.test(" \u3000")    # true (incl. ideographic space)

# Negation: \P{...} (uppercase P)
/^\P{L}+$/u.test("123!")        # true (no letters)

# Specific scripts
\p{Script=Han}      # CJK characters
\p{Script=Latin}    # Latin alphabet
\p{Script=Greek}    # Greek
\p{Script=Cyrillic} # Russian etc.

# Categories (long form)
\p{Letter}    # same as \p{L}
\p{Lowercase_Letter}  # same as \p{Ll}
\p{Uppercase_Letter}  # same as \p{Lu}

# Emoji
\p{Emoji}     # any emoji character
\p{Emoji_Presentation}  # emoji with emoji presentation

# JavaScript support: ES2018+
# Python: needs 'regex' module (PyPI) or Python 3.13+
# PHP: /u flag with \p{L} etc.
# Java: \p{L} (Unicode by default)
# .NET: \p{L} by default
# Go (RE2): \p{L} by default

문자 속성 \p{L}

\p{L}은 모든 문자 체계의 문자와 일치합니다. 라틴, 그리스, 키릴, CJK, 아랍, 히브리 등입니다. 하위 분류: \p{Lu}(대문자), \p{Ll}(소문자), \p{Lo}(기타 — CJK 표의 문자, 아랍). 유니코드 인식 단어 매칭에는 \w+(기본 ASCII 전용) 대신 \p{L}+를 사용하세요.

regex
# \p{L} matches any letter in any script

# Match any word (Unicode-aware)
/\p{L}+/gu          # matches "hello", "日本語", "Привет"

# Match a single Latin letter
/\p{Script=Latin}/u

# Specific letter categories
\p{Lu}  # uppercase letter (A, B, Ω, Ψ)
\p{Ll}  # lowercase letter (a, b, ω, ψ)
\p{Lt}  # titlecase letter (Dž, Lj - rare)
\p{Lm}  # modifier letter (ˆ, ˇ)
\p{Lo}  # other letter (CJK, Arabic, Hebrew)

# JavaScript examples
"Hello Ωμέγα".match(/\p{L}+/gu)  # ["Hello", "Ωμέγα"]
"hello WORLD".match(/\p{Lu}+/gu)  # ["WORLD"]
"Hello".match(/\p{Ll}+/gu)        # ["ello"]

# Validate Unicode identifier
/^[\p{L}_][\p{L}\p{N}_]*$/u

# Match Capitalized Unicode word
/\p{Lu}\p{Ll}*/u   # "Hello", "Ωμέγα" (if Ω is uppercase)

# Count letters
const text = "Hello 世界 123";
const letters = text.match(/\p{L}/gu) || [];
// ["H", "e", "l", "l", "o", "世", "界"]

# Python (with 'regex' module)
import regex
regex.findall(r"\p{L}+", "Hello 世界")

# Split on non-letters (Unicode-aware)
"hello, world!世界".split(/\P{L}+/u)  # ["hello", "world", "世界"]

숫자 속성 \p{N}

\p{N}은 모든 숫자와 일치합니다. ASCII 0-9, 아랍-인도 숫자 ٠-٩, 데바나가리 ०-९, 로마 숫자, 분수 등입니다. 하위 분류: \p{Nd}(십진 숫자), \p{Nl}(Ⅷ 같은 문자 숫자), \p{No}(½, ² 같은 기타). ASCII만 원하면 [0-9]를 명시하세요. JS의 \d는 /u 없으면 ASCII이고, /u가 있으면 유니코드 숫자와 일치합니다.

regex
# \p{N} matches any number character in any script

# Match digits in any script
\p{N}+   # 123, ١٢٣ (Arabic-Indic), १२३ (Devanagari), etc.

# Subcategories
\p{Nd}  # decimal digit (0-9, ٠-٩ Arabic, ०-९ Devanagari)
\p{Nl}  # letter number (Roman numerals Ⅷ, etc.)
\p{No}  # other number (fractions ½, superscripts ²)

# JavaScript
"Price: 123, Arabic: ١٢٣".match(/\p{N}+/gu)
# ["123", "١٢٣"]

# Match only ASCII digits
/[0-9]/         # ASCII digit
/\d/           # in JS without /u: same as [0-9]
/\d/u          # with /u: matches Unicode digits too!

# ASCII-only number (always)
/[0-9]+/

# Match decimals (with optional decimal point)
/\p{N}+(?:\.\p{N}+)?/u

# Count digits (any script)
const text = "123 ١٢٣";
const digits = text.match(/\p{Nd}/gu) || [];
// ["1", "2", "3", "١", "٢", "٣"]

# Python
import regex
regex.findall(r"\p{N}+", "123 ١٢٣")

# Extract version numbers (ASCII only)
const v = "Version 1.2.3 released";
v.match(/[0-9]+(?:\.[0-9]+)+/)[0]  # "1.2.3"

# Currency with Unicode digits
/\p{Sc}\p{Nd}+(?:\.\p{Nd}+)?/u  # $123.45, €١٢٣.٤٥

이모지 매칭

\p{Emoji}(JS는 ES2018+, /u 필요)로 이모지를 일치시킵니다. 흔한 범위: \u{1F600}-\u{1F64F}(이모티콘), \u{1F300}-\u{1F5FF}(기호). 실제 이모지 매칭은 복잡합니다. ZWJ 시퀀스(👨‍👩‍👧)는 여러 코드 포인트를 결합하고, 변형 선택자(\uFE0F)는 표시를 바꾸며, 국기는 지역 표시자 쌍입니다. 완전한 이모지 매칭에는 전용 라이브러리를 사용하세요.

regex
# Match emoji (requires /u flag in JS)

# Simple emoji property
/\p{Emoji}/u           # any emoji character
/^\p{Emoji}+$/u.test("👋😀🎉")  # true

# Emoji with presentation (displayed as emoji, not text)
/\p{Emoji_Presentation}/u

# Common emoji ranges (for older engines without \p{Emoji})
/[\u{1F600}-\u{1F64F}]/u  # emoticons
/[\u{1F300}-\u{1F5FF}]/u  # symbols & pictographs
/[\u{1F680}-\u{1F6FF}]/u  # transport & map
/[\u{1F700}-\u{1F77F}]/u  # alchemical
/[\u{2600}-\u{26FF}]/u    # misc symbols (☀ ☂ ☎)
/[\u{2700}-\u{27BF}]/u    # dingbats (✁ ✂ ✃)

# Combined range
/[\u{1F300}-\u{1F9FF}\u{2600}-\u{27BF}]/u

# Count emoji in text
const text = "Hello 👋😀 world 🎉";
const emoji = text.match(/\p{Emoji}/gu) || [];
// ["👋", "😀", "🎉"]

# Strip emoji from text
text.replace(/\p{Emoji}/gu, "")  # "Hello  world "

# Emoji with modifiers (skin tones, ZWJ sequences)
# 👨‍👩‍👧 is actually multiple code points joined by ZWJ (\u200D)
/\p{Emoji}(?:\u200D\p{Emoji})*/u
# matches a ZWJ sequence as one emoji

# Emoji with variation selector (\uFE0F)
/\p{Emoji}\uFE0F?/u  # optional variation selector

# Flag emoji (regional indicators)
/[\u{1F1E6}-\u{1F1FF}]{2}/u  # 🇺🇸, 🇨🇳, etc.

# JavaScript support: ES2018+ (\p{Emoji})
# Python: needs 'regex' module
# PHP: /u flag with \p{Emoji}
19

언어별 차이

JavaScript

JavaScript 정규식: 리터럴 /pattern/flags가 가장 흔합니다. ES2018+는 후방 탐색, 명명 그룹, 유니코드 속성 이스케이프를 추가했습니다. ES2020+는 matchAll(/g+exec보다 안전)을 추가했습니다. /g와 exec()의 lastIndex 함정을 주의하세요. 동적 패턴에는 RegExp 생성자를 사용하세요. 사용자 입력으로 패턴을 만들 때는 메타 문자를 이스케이프하세요.

regex
# JavaScript regex features

# Literal syntax (preferred for static patterns)
const re = /pattern/flags;

# Constructor (for dynamic patterns)
const re2 = new RegExp("pattern", "flags");

# Flags: g (global), i (case-insensitive), m (multiline),
#        s (dotAll, ES2018+), u (Unicode), y (sticky)

# Methods
/pattern/.test(string)             # boolean
string.match(/pattern/)            # match info or array
string.match(/pattern/g)           # array of matches (no groups)
[...string.matchAll(/pattern/g)]   # iterator (ES2020+)
string.replace(/pattern/, "repl")  # replace first
string.replace(/pattern/g, "repl") # replace all
string.split(/pattern/)            # split
string.search(/pattern/)           # index of first match or -1

# Named groups (ES2018+)
const m = "2024-01-15".match(/(?<y>\d{4})/);
m.groups.y  # "2024"

# Lookbehind (ES2018+, not supported in old Safari)
/(?<=\$)\d+/.test("$100")  # true

# Unicode property escapes (ES2018+)
/^\p{L}+$/u.test("Hello")  # true

# Gotcha: /g with exec() maintains lastIndex
const r = /a/g;
r.exec("aaa"); r.lastIndex  # 1
r.exec("aaa"); r.lastIndex  # 2
# Use matchAll or reset lastIndex to 0

# String.prototype.replaceAll (ES2021+)
"a-b-c".replaceAll("-", "+")  # "a+b+c"

# Escape function for literal strings
function escapeRegExp(s) {
  return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}

Python

Python의 re 모듈은 이중 이스케이프를 피하려고 원시 문자열(r"")을 사용합니다. 주요 함수: search(어디서든), match(시작 고정), fullmatch(전체), findall, finditer, sub(교체), split. Python 전용 명명 그룹 문법: (?P<name>...)와 (?P=name). Python 3.11+는 정규식 타임아웃을 추가했습니다. 서드파티 'regex' 모듈은 \p{...} 속성과 재귀 패턴을 추가합니다.

regex
# Python regex (re module)

import re

# Raw strings (r"...") avoid double-escaping
pattern = r"\bword\b"
re.search(pattern, text)  # find anywhere
re.match(pattern, text)   # anchored at start
re.fullmatch(pattern, text)  # entire string

# Flags (constants)
re.IGNORECASE  # or re.I - case-insensitive
re.MULTILINE   # or re.M - ^ $ match line boundaries
re.DOTALL      # or re.S - . matches newline
re.VERBOSE     # or re.X - allow whitespace and comments
re.ASCII       # or re.A - ASCII-only for \w \d \s
re.UNICODE     # default in Python 3

# Combine flags with |
re.search(pattern, text, re.IGNORECASE | re.MULTILINE)

# Inline flags
(?i)pattern    # case-insensitive
(?im)pattern   # multiple inline flags
(?i:pattern)   # scoped (Python 3.6+)

# Common functions
re.search(pattern, string, flags)  # Match or None
re.match(pattern, string, flags)   # Match or None (anchored)
re.fullmatch(pattern, string)      # Match or None (entire)
re.findall(pattern, string)        # list of matches or tuples
re.finditer(pattern, string)       # iterator of Match objects
re.sub(pattern, repl, string, count=0)  # replace
re.split(pattern, string, maxsplit=0)   # split

# Named groups (Python-specific syntax)
(?P<name>pattern)        # capture
(?P=name)                # backreference
\g<name>                 # in replacement

# Compiled pattern (faster for reuse)
p = re.compile(r"\d+", re.IGNORECASE)
p.search("abc 123")

# Timeout (Python 3.11+)
re.compile(r"(a+)+").match(long_string, timeout=1.0)

# Third-party 'regex' module adds: \p{...}, variable lookbehind, recurs

Java

Java 정규식은 문자열에서 이중 이스케이프가 필요합니다(\d는 "\\d"). Pattern/Matcher는 컴파일과 매칭을 분리합니다. find()는 다음 매치로 이동하고, matches()는 전체 문자열 일치를 요구하며, lookingAt()은 시작에 고정됩니다. Java는 소유 수량자(a++)와 원자 그룹(?>...)을 지원합니다. 후방 탐색은 고정 길이여야 합니다. Java 7+는 명명 그룹을 추가했습니다.

regex
# Java regex (java.util.regex)

import java.util.regex.*;

# Compile pattern (double-escape backslashes in Java strings)
Pattern p = Pattern.compile("\\bword\\b");
Matcher m = p.matcher("a word here");

# Methods
m.find()        # finds next match (boolean)
m.matches()     # entire string matches (boolean)
m.lookingAt()   # matches at start (boolean)
m.group()       # entire match
m.group(1)      # first capture group
m.start()       # start index
m.end()         # end index

# Replace
m.replaceAll("repl")       # all matches
m.replaceFirst("repl")     # first match only

# String convenience methods (compile internally)
"abc".matches("a.c")           # true (entire string)
"a-b-c".replaceAll("-", "+")   # "a+b+c" (regex)
"a-b-c".replace("-", "+")      # "a+b+c" (literal)
"a-b-c".split("-")             # ["a", "b", "c"]

# Flags (constants)
Pattern.CASE_INSENSITIVE  # or 1 << 1
Pattern.MULTILINE         # or 1 << 2
Pattern.DOTALL            # or 1 << 3
Pattern.UNICODE_CHARACTER_CLASS  # or 1 << 7
Pattern.COMMENTS          # or 1 << 4

# Combine flags with |
Pattern.compile("abc", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE)

# Inline flags
(?i)abc       # case-insensitive
(?id)abc      # multiple
(?i:abc)      # scoped

# Named groups (Java 7+)
(?<name>pattern)
\k<name>      # backreference
${name}       # in replacement

# Lookbehind: must be FIXED length
(?<=ab|cd)x   # OK (same length)
(?<=ab|abc)x  # ERROR (different length)

# Possessive quantifiers (Java supports)
a++  a*+  a?+  a{2,5}+

# Atomic groups
(?>a|b)

# Stream matches (Java 9+)
p.matcher(input).results().forEach(m -> ...);

PHP(PCRE)

PHP는 구분자 문법(/pattern/flags)의 PCRE를 사용합니다. 함수: preg_match(단일 매치), preg_match_all(전체), preg_replace, preg_replace_callback, preg_split. 플래그는 닫는 구분자 뒤에 옵니다(i, m, s, x, u). 명명 그룹: (?P<name>...) 또는 (?<name>...). UTF-8에는 /u 플래그를 사용하세요. 패턴에 /가 있으면 다른 구분자(#, ~)를 선택하세요.

regex
# PHP regex (PCRE - Perl-Compatible Regular Expressions)

# Pattern delimited by / (or other chars like #, ~, |)
/^[a-z]+$/i
'~^[a-z]+$~i'

# Functions
preg_match('/pattern/', $subject)            # 0 or 1 (bool-ish)
preg_match('/pattern/', $subject, $matches)  # fills $matches
preg_match_all('/pattern/', $subject, $matches)  # count, fills $matches
preg_replace('/pattern/', 'repl', $subject)  # replace all
preg_replace_callback('/pattern/', fn, $subject)  # function replace
preg_split('/pattern/', $subject)            # split

# Flags after closing delimiter
i  # case-insensitive
m  # multiline (^ $ at line boundaries)
s  # dotall (. matches newline)
x  # extended (whitespace ignored, # comments)
u  # treat pattern and subject as UTF-8

# Combine: /pattern/imsu

# $matches structure
preg_match('/(\w+)@(\w+)/', 'user@host', $m);
# $m[0] = "user@host" (whole match)
# $m[1] = "user" (group 1)
# $m[2] = "host" (group 2)

# preg_match_all with PREG_SET_ORDER
preg_match_all('/(\w+)/', 'a b c', $m, PREG_SET_ORDER);
# $m[0] = ["a", "a"], $m[1] = ["b", "b"], ...

# Named groups
/(?P<name>\w+)/       # PHP/PCRE style (also (?<name>...))
/(?<name>\w+)/        # alternative
\k<name>              # backreference
$matches['name']       # access by name

# Replacement references
$1, $2          # numbered groups
\1, \2          # also valid
${1}            # unambiguous (e.g., ${1}0 to avoid $10)

# Unicode properties (with /u flag)
preg_match('/^\p{L}+$/u', 'Hello')

# PCRE-specific features
(?P<name>...)   # named (Python-compatible)
(?<name>...)    # named (alternative)
(?P=name)       # backreference
(?>...)         # atomic group
a++             # possessive
\R              # any line break sequence
(*FAIL)         # force fail
(*SKIP)         # skip in findall

# Delimiter alternatives (when pattern contains /)
# /pattern/, #pattern#, ~pattern~, |pattern|, !pattern!

Go(RE2)

Go는 RE2를 사용합니다. 선형 시간 엔진이며 역참조, 후방 탐색, 원자 그룹, 소유 수량자가 없습니다. 대신 RE2는 치명적 역추적에 면역입니다. 메서드: MatchString(불리언), FindString(첫 번째), FindAllString(전체), ReplaceAllString, Split. 이중 이스케이프를 피하려면 원시 문자열(백틱)을 사용하세요. 플래그는 인라인만 가능합니다: (?i), (?m), (?s).

regex
# Go regex (RE2 engine - linear time, no backreferences)

import "regexp"

# Compile pattern (must use raw string `...` or escape backslashes)
re := regexp.MustCompile(`\bword\b`)
re := regexp.MustCompile("\\bword\\b")  # with escaping

# Methods
re.MatchString("a word here")     # bool
re.FindString("a word here")      # first match or ""
re.FindAllString("a b c", -1)     # []string of all matches
re.FindStringSubmatch("user@host") # [whole, group1, group2, ...]
re.FindAllStringSubmatch(text, -1) # [][]string
re.FindStringIndex("abc")         # [start, end] or nil
re.ReplaceAllString("a-b-c", "+") # "a+b+c"
re.ReplaceAllStringFunc(text, func)
re.Split("a,b,c", -1)             # []string

# -1 means "all matches"; positive N limits splits/matches

# Named groups
re := regexp.MustCompile(`(?P<year>\d{4})-(?P<month>\d{2})`)
m := re.FindStringSubmatch("2024-01")
# m[0]="2024-01", m[1]="2024", m[2]="01"

# Access by name
re.SubexpNames()  # ["", "year", "month"]

# IMPORTANT: RE2 limitations
# - NO backreferences (\1)
# - NO atomic groups (?>...)
# - NO possessive quantifiers (a++)
# - NO lookbehind (?<=...)
# - NO lookahead (?!...) — but (?=...) IS supported
# - NO recursive patterns
# - NO conditional patterns

# In exchange: linear-time guarantee (no catastrophic backtracking)

# Flags (inline only — no separate flags arg)
(?i)           # case-insensitive
(?m)           # multiline
(?s)           # dotall
(?i)pattern    # applies to whole pattern
(?i)abc(?-i)def  # scoped (PCRE-style, not in Go)

# Compile vs MustCompile
re, err := regexp.Compile(pattern)  # returns error
re := regexp.MustCompile(pattern)   # panics on error

# Quote literal string for safe regex use
regexp.QuoteMeta("1.5")  # "1\\.5"

.NET / C#

.NET 정규식은 기능이 풍부합니다. 명명 그룹 (?<name>...), 밸런싱 그룹(독특하며 균형 잡힌 괄호 같은 중첩 구조 일치 가능), 타임아웃, 함수 교체용 MatchEvaluator. 이중 이스케이프를 피하려면 축자 문자열(@"")을 사용하세요. RegexOptions.Singleline은 dotall을 뜻합니다(혼란스러운 이름). .NET은 주요 엔진 중 가장 많은 정규식 기능을 지원합니다.

regex
# .NET regex (System.Text.RegularExpressions)

using System.Text.RegularExpressions;

# Static methods
Regex.IsMatch("abc", "a.c")                 # bool
Regex.Match("abc", "a.c")                   # first match
Regex.Matches("a1 b2", "\d+")              # all matches
Regex.Replace("a-b-c", "-", "+")            # "a+b+c"
Regex.Split("a,b,c", ",")                   # string[]

# Instance (compiled for reuse)
Regex re = new Regex("\\d+", RegexOptions.Compiled);
re.Match("abc 123");
re.Matches("abc 123 456");
re.Replace("abc 123", "X");

# Flags (RegexOptions enum)
RegexOptions.IgnoreCase      # i
RegexOptions.Multiline       # m
RegexOptions.Singleline      # s (dotall - confusing name!)
RegexOptions.ExplicitCapture # only named groups capture
RegexOptions.IgnorePatternWhitespace  # x (extended)
RegexOptions.Compiled        # compile to IL (faster, slower startup)
RegexOptions.CultureInvariant

# Combine with |
new Regex("abc", RegexOptions.IgnoreCase | RegexOptions.Multiline)

# Named groups (.NET style)
(?<name>pattern)       # capture
(?<name1>...) (?<name2>...)  # multiple
\k<name>               # backreference
${name}                # in replacement

# Alternation in group names (balancing groups - .NET specific)
(?<name1-name2>...)    # pop name2 stack into name1

# Group access
Match m = re.Match("2024-01-15");
m.Groups["year"].Value
m.Groups[1].Value

# Replace with MatchEvaluator (function)
Regex.Replace("abc", "\w", m => m.Value.ToUpper())  # "ABC"

# Timeouts (.NET 4.5+)
Regex re = new Regex("a+", RegexOptions.None, TimeSpan.FromSeconds(1));

# Unicode supported by default
Regex.IsMatch("Hello", @"\p{L}+")  # true (note: @"" verbatim string)

# Verbatim strings (@"...") avoid double-escaping
@"\d+"    # same as "\\d+" but cleaner

# Surprisingly powerful: balancing groups for nested matching
# Can match balanced parentheses (unique to .NET)
 @"((?:[^()]+|(?<Open>\()|(?<Close-Open>\)))*)"
20

고급 기법

원자 그룹

원자 그룹 (?>...)은 한 번 일치한 그룹으로의 역추적을 막습니다. 성능(치명적 역추적 회피)과 매치 고정에 유용합니다. PCRE, Java, .NET, Python의 'regex' 모듈에서 지원하며 JavaScript에는 없습니다. JS 대안: 패턴을 리팩터링하거나 구체적 문자 클래스로 역추적을 피하세요.

regex
# Atomic group: (?>...) - once matched, NO backtracking into it
# Supported in PCRE, Java, .NET — NOT in JavaScript or Python's re

# Greedy with backtracking
\d+a           # in "123a", \d+ takes "123", then backtracks to "12" if needed
(?>\d+)a       # atomic: \d+ takes "123" and CANNOT give back

# When atomic helps: prevent catastrophic backtracking
# Dangerous: (a+)+b on "aaaa...!"
# Safe (atomic): (?>a+)+b  or  (?>a+b)

# Use case: prevent unwanted backtracking in alternation
# Without atomic: tries each alternative, backtracks on fail
(?>cat|category)   # if "cat" matches, won't try "category"

# Practical: match HTML tag without backtracking issues
(?><[a-z][a-z0-9]*\b[^>]*>)

# Quoted string without backtracking issues
(?>"[^"]*")

# Java
Pattern p = Pattern.compile("(?>\\d+)a");

# PHP/PCRE
preg_match('/(?>\d+)a/', '123a')

# .NET
new Regex("(?>\d+)a")

# Python: not in re module; use 'regex' module
import regex
regex.search(r"(?>\d+)a", "123a")

# JavaScript: NOT supported
# Use possessive quantifiers (also not in JS) or refactor pattern

소유 수량자

소유 수량자(a++, a*+, a?+)는 탐욕적과 비슷하지만 일치한 것을 절대 돌려주지 않습니다. 원자 그룹과 동등하지만 더 짧습니다. Java와 PCRE에서 지원하며 .NET, JavaScript, Python의 re에는 없습니다. 이식 가능한 대안은 원자 그룹 (?>...)입니다. 둘 다 불필요한 역추적을 피해 치명적 역추적을 막습니다.

regex
# Possessive: a++ a*+ a?+ a{n,m}+
# Like greedy but NEVER gives back (no backtracking)

# Greedy (gives back if needed)
\d+a    # "123a": \d+ takes "123", matches a
\d+x    # "123x": \d+ takes "123", then x matches

# Possessive (never gives back)
\d++a   # "123a": \d+ takes "123", matches a
\d++x   # "123x": \d+ takes "123", x fails - NO backtrack, FAIL

# When possessive helps: avoid catastrophic backtracking
# Dangerous: (a+)+  on "aaaaaa!"
# Possessive: (a++)+  or  (?>a+)+
# Both prevent exponential backtracking

# Common possessive patterns
"[^"]*"++     # possessive quoted string
<[a-z]++>      # possessive tag name
\d++\.\d++   # possessive decimal

# Java supports possessive quantifiers
Pattern.compile("\\d++a");

# PHP/PCRE supports possessive
preg_match('/\d++a/', '123a')

# .NET: does NOT support possessive quantifiers directly
# Use atomic groups instead: (?>\d+)a

# Python 're': NOT supported
# Python 'regex' module: supports \d++ ? Actually no, use (?>\d+)

# JavaScript: NOT supported
# Use atomic groups (also not in JS) or refactor

# Comparison: possessive vs atomic
\d++       # possessive quantifier (Java, PCRE)
(?>\d+)    # atomic group (Java, PCRE, .NET)
# Both prevent backtracking; possessive is shorter syntax

조건부 패턴

조건부 패턴 (?(condition)yes|no)은 그룹이 일치했는지 또는 전방 탐색이 성공했는지에 따라 다른 패턴을 일치시킵니다. PCRE, .NET, Perl, Python의 'regex' 모듈에서 지원하며 JavaScript와 Java에는 없습니다. 미지원 엔진의 우회: 선택, 코드에서 여러 패턴 결합, 탐색 사용.

regex
# Conditional: (?(condition)yes-pattern|no-pattern)
# PCRE, .NET, Perl — NOT JavaScript or Python's re

# Conditional based on group match
(?(1)yes|no)    # if group 1 matched, use yes-pattern; else no-pattern
(?(<name>)yes|no)  # named group version

# Example: match "Mr. Smith" or "Smith" based on title presence
(Mr\.\s+)?(\w+)(?(1)\s+\2|)  # if title, require last name repeated?

# Practical: optional separator
# If first separator was -, second must be -
# If first was /, second must be /
(\d{4})([-/]?)(\d{2})(?(2)\2|[-/]?)(\d{2})

# Conditional based on lookahead
(?(?=\d)\d+|[a-z]+)  # if next is digit, match digits; else letters

# Python 'regex' module supports conditionals
import regex
regex.search(r"(?(1)yes|no)", text)

# .NET supports conditionals
new Regex("(?(1)yes|no)")

# PCRE/PHP supports conditionals
preg_match('/(?(1)yes|no)/', $text)

# Java: does NOT support conditionals directly
# Use alternation and lookarounds as workaround

# JavaScript: NOT supported
# Refactor with alternation:
# (?(1)A|B) becomes: (?:group1A|B) in some cases
# Or use two separate patterns and combine in code

# Real-world: parse key-value where value is conditional
# If key is "url", value must be URL; if "count", value must be number
(url|count):(?(?<=url:)https?://\S+|\d+)

재귀(PCRE)

재귀 패턴 (?R)은 균형 잡힌 괄호, 중첩 HTML, 수학 표현식 같은 중첩 구조를 일치시킵니다. PCRE/Perl/Python의 'regex' 모듈이 직접 지원합니다. .NET은 독특한 '밸런싱 그룹'을 대신 사용합니다. JavaScript와 Java는 정규식 재귀를 지원하지 않으므로 중첩 구조에는 파서나 스택 기반 코드를 사용하세요.

regex
# Recursive patterns: (?R) or (?N) - match nested structures
# PCRE, Perl, .NET (balancing groups) — NOT JS, Java, Python re

# Match balanced parentheses (PCRE)
\((?:[^()]+|(?R))*\)
# Matches: "(a)", "(a(b)c)", "((a)(b))", etc.

# Named recursion (PCRE)
(?<paren>\((?:[^()]+|(?&paren))*\))

# Match nested HTML/XML tags (PCRE)
(?<tag><([a-z]+)(?:[^>]+)>[^<]*</\2>|<([a-z]+)(?:[^>]+)>(?R)*</\3>)

# Python 'regex' module supports recursion
import regex
regex.search(r"\((?:[^()]+|(?R))*\)", "(a(b)c)")

# .NET: use balancing groups instead of recursion
# Match balanced parens:
\((?:[^()]+|(?<Open>\()|(?<Close-Open>\)))*\)
# More complex but powerful

# PHP/PCRE
preg_match('/\((?:[^()]+|(?R))*\)/', '(a(b)c)')

# JavaScript: NOT supported
# Use a parser or stack-based approach in code
function matchBalanced(s) {
  let depth = 0, start = -1, results = [];
  for (let i = 0; i < s.length; i++) {
    if (s[i] === "(") { if (depth === 0) start = i; depth++; }
    else if (s[i] === ")") {
      depth--;
      if (depth === 0 && start !== -1) {
        results.push(s.slice(start, i + 1));
        start = -1;
      }
    }
  }
  return results;
}

# Java: NOT supported
# Use third-party library or stack-based parser

성능 팁

정규식 성능: 재사용을 위해 패턴을 컴파일하고, 구체적으로 작성하며(., 회피), 가능하면 앵커를 쓰고, 비캡처 그룹을 사용하고, 치명적 역추적을 피하고, 최소 일치 수량자보다 부정 클래스를 선호하고, 선택지를 발생 가능성 순으로 정렬하고, 신뢰할 수 없는 입력에는 타임아웃을 설정하세요. 충분한 경우에는 String 메서드(trim, split, indexOf)를 사용하세요. 종종 정규식보다 빠릅니다.

regex
# 1. Compile patterns for reuse (Python, Java)
import re
p = re.compile(r"\d+")  # compile once
for line in lines:
    p.search(line)  # reuse

# 2. Be specific - avoid . when you know the char class
# Bad:  .*
# Good: [a-z]*  or  \w*  or  [^,]*
# Faster and clearer intent

# 3. Anchor when possible
# Bad:  \d+
# Good: ^\d+$  (if validating entire string)
# Anchors let the engine fail fast

# 4. Use non-capturing groups when you don't need captures
# Bad:  (\d{1,3}\.){3}\d{1,3}
# Good: (?:\d{1,3}\.){3}\d{1,3}
# Saves memory and time

# 5. Avoid catastrophic backtracking
# Bad:  (a+)+b  on "aaaa...!"
# Good: a++b (possessive) or (?>a+)b (atomic) or a*b

# 6. Prefer negated classes over lazy quantifiers for delimited content
# Slower: ".*?"
# Faster: "[^"]*"

# 7. Use atomic groups / possessive quantifiers when safe
(?>\d+)  # no backtracking needed for digits

# 8. Order alternation by likelihood
# Bad:  (rare|common)
# Good: (common|rare)
# Engine tries left to right

# 9. Avoid nested quantifiers on overlapping alternatives
# Bad:  (a|a)*b
# Good: a*b

# 10. Set timeouts for untrusted input (Python 3.11+, .NET 4.5+)
re.compile(pattern).match(input, timeout=1.0)

# 11. Use RE2 for untrusted patterns (Go, or libraries)
# Linear time, immune to catastrophic backtracking
# Trade-off: no backreferences

# 12. Benchmark with realistic data
# Use timeit (Python) or performance.now() (JS)

# 13. Avoid lookahead/lookbehind when a simpler pattern works
# Bad:  (?<=\$)\d+
# Good: \$(\d+) and use group 1 (often faster)

# 14. Use String methods for simple operations
# Bad:  text.replace(/^\s+|\s+$/g, "")
# Good: text.trim()  (much faster)

Was this helpful?

Learning path

Learn from scratch

Learn this language from the ground up with structured lessons.