はじめに
基本の構文
パターンマッチングのための特殊文字を使うのが、正規表現です。任意の文字に一致するのが、. で、文字クラスを定義するのが []、よくある集合の省略形が、\d、\w、\s です。否定のためには、[] の内側で ^ を使いましょう。
# 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メタ文字
特殊な意味を持つのが、メタ文字です。リテラルに一致させるには、バックスラッシュを接頭辞に付けましょう。文字クラス [] の内側で、エスケープを必要とするのは、]、\、^、- だけです(そして - は、先頭/末尾にないときだけです)。
# 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] のような文字クラスのトリックを使いましょう。
# 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 です。
# 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() です。意図に合う正しい関数を選びましょう。
# 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文字クラス
文字セット [abc]
列挙された任意の単一文字に一致する文字セットを定義するのが、角括弧です。[] の内側では、ほとんどのメタ文字(. * + ? など)が特殊な意味を失い、リテラルに一致します。内側で特殊なのは、]、\、^、- だけです。
# 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 まで」のパターンの一致に有用です。
# 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]
2 文字の間のハイフンが、文字コードに基づくレンジを作ります。低から高へ行かなければならないのが、レンジです。セットでリテラルのハイフンに一致させるには、先頭/末尾に置くか、エスケープしましょう。Z と a の間の非文字の文字を含むため、[A-z] は避けましょう。
# 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 のデフォルトや、/u 付きの JS の)Unicode モードでは、\d と \w が ASCII 以上に一致します。ASCII 専用のためには、Python では re.ASCII を、明示的に [0-9] を使いましょう。
# 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] のように明示的に組み合わせましょう。
# 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クラスの組み合わせ
レンジ、省略形、リテラルを混ぜられるのが、文字クラスです。(レンジと、先頭の ^ を除き)順序は効きません。email、ファイル名、識別子のような実用的なパターンを構築するのに使いましょう。
# 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}量指定子
アスタリスク *(ゼロ以上)
先行する要素のゼロ以上に一致するのが、* です。デフォルトで貪欲です — 可能な限り多く一致します。遅延させるには、後に ? を加えましょう(*?)。https?:// のような「省略可能な」パターンのために、? と共に使われるのが、よくあります。
# * 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 以上)
少なくとも 1 つの一致を要求するのが(ゼロを許す * と違い)、+ です。単語(\w+)、数値(\d+)、空白の連続(\s+)のような「1 以上」のパターンに有用です。最初の一致で止まるのが、遅延版の +? です。
# + 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"疑問符 ?(ゼロか 1)
先行する要素を省略可能にする(0 か 1)のが、? です。別の量指定子の後に置かれると(*?、+?、??)、その量指定子を遅延させます。省略可能な文字、符号、区切り、「Nov」/「November」のような短い/長い形式に有用です。
# ? 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 まで)です。有効な量指定子を形成しなければ、リテラルとして { を扱うのが、ほとんどのエンジンです。? が加えられない限り、常に貪欲です。
# 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/テキストで予想外の一致を引き起こし得ます。問題を避けるためには、遅延(*?、+?)を使うか、文字クラスでより具体的に。
# 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"遅延の量指定子
(非貪欲か消極的とも呼ばれる)可能な限り少なく一致し、必要なときだけ拡大するのが、遅延の量指定子です。引用符/タグの間のコンテンツのような、最短の一致を見つけるのに使いましょう。引用符付きの文字列には、「'[^']*'」が、「'.*?'」よりしばしばより明快で速いです。
# 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アンカーと境界
開始アンカー ^
文字列の先頭に一致するのが(/m フラグ付きでは、各行の先頭)、^ です。幅ゼロのアサーションであり、文字を消費しません。文字クラスを否定する、[] の内側の ^ と混同しないようにしましょう。文字列全体を検証するには、^...$ を。
# ^ 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 付きでは、行末)、$ です。文字列全体がパターンに一致することを検証するには、^...$ を組み合わせましょう。選択には注意しましょう:^a|b$ が (^a) OR (b$) を意味するため、^(a|b)$ か ^(?:a|b)$ を使いましょう。
# $ 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
\w(単語文字)と \W(非単語文字)の間の境界か、文字列の縁に一致する、幅ゼロのアサーションが、\b です。部分文字列に一致せず、完全な単語に一致させるのに完璧です。単語文字であるため、\b にとって「foo_bar」が 1 単語です。
# \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」のような、特定のケースに強力です。
# \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 の ^ $ です。
# 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グループとキャプチャ
キャプチャグループ ()
後の使用のために、一致したテキストを記録するキャプチャグループを作るのが、括弧の () です。1 から始まる左から右へ番号付けされるのが、グループです。一致の一部を取り出したり、置換文字列や後方参照で後から参照するのに使いましょう。
# 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"グループの番号付け
開き括弧の位置により、左から右へ番号付けされるのが、グループです。内側のグループの前に来るのが、外側/ネストしたグループです。異なるのが、置換の構文です:$1 が、JS/Java で、\1(か \g<1>)が、Python で、$1 と \1 の両方が、PHP で許されます。
# 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)非キャプチャ((?:...))
キャプチャを必要としないグループ化には、(?:...) を使いましょう。メモリを節約し、キャプチャグループの番号付けを予測可能に保ち、意図を合図します。取り込まれた値が無関係なサブパターン上の選択や量指定子のとき、特に重要です。
# (?:...) 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>...))
パターンを自己文書化させるのが、(JS/.NET の)(?<name>...) か(Python/PCRE の)(?P<name>...) です。置換での名前による参照が(JS では $<name>、Python では \g<name>)、後方参照が(JS では \k<name>、Python では (?P=name))、です。
# 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"}選択 |
いくつかのパターンのうちの 1 つに一致するのが、選択の | です。非常に低い優先順位を持つため、スコープするには括弧を使いましょう。左から右へ選択肢を試み、全体の一致が成功することを許す最初のものを選ぶのが、エンジンです。選択肢が重なるとき、順序が効きます。
# | 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 のタグのペアの一致、繰り返しの単語の発見、一貫した区切りの確保です。後方参照が一致しなければならないのは、グループが取り込んだものと正確に、です。
# \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)非キャプチャグループ
基本の非キャプチャ
キャプチャを作らずグループ化するのが、(?:...) です。選択や量指定子のためのグループ化が必要だが、一致した値を気にしないときは、いつでも使いましょう。グループの番号付けを予測可能に保ち、わずかに速いです。
# (?: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)量指定子との併用
一致したテキストを保たずサブパターンを繰り返したいとき、量指定子と良く組み合わさるのが、非キャプチャグループです。複雑なパターンの特定の部分を取り出すとき、キャプチャグループの番号を予測可能に保つには、これが不可欠です。
# 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ネストしたグループ
キャプチャするものと自由に混ぜられるのが、非キャプチャグループです。開き括弧の順で依然番号付けされるのが、キャプチャですが、番号を消費しないのが、非キャプチャグループです。一部の部分だけが効くとき、キャプチャ番号を緊密に保つのに、これを使いましょう。
# 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)パフォーマンスの利得
取り込まれたテキストをエンジンが保存しないため、わずかに速くメモリを節約するのが、非キャプチャグループ((?:...))です。一致ごとの利得が小さいですが、大きなテキストの上の密なループでは効き得ます。取り込まれた値を参照する必要がないときは、いつでもこれを使いましょう。
# 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)よくあるユースケース
輝くのが:選択のグループ化、サブパターンへの量指定子の適用、省略可能なセクション、キャプチャ番号のきれいな維持です。グループ化のデフォルトは、(?:...) にしましょう — 実際にテキストを取り出すか後方参照するときだけ、() を使いましょう。
# 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先読みと後読み
肯定の先読み(?=)
文字を消費せず、続くものがパターンに一致すると断言するのが、肯定の先読み(?=...)です。特定のものが続くときだけパターンを見つけるのや、パスワードのルールでの「数字を含むべき」のような検証に有用です。
# (?=...) - 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 を含んではならない」など)、何かが続かないときだけの一致(例:「u」が続かない「q」)。
# (?!...) - 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 です。
# (?<=...) - 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否定の後読み((?<!))
先行するものが一致し「ない」と断言するのが、否定の後読み((?<!...))です。コンテキストに基づくマッチの除外に有用です(「$ が前にない数を見つける」や「より大きい識別子の一部でない単語を見つける」など)。古いエンジンでは、肯定の後読みと同じ長さの制限です。
# (?<!...) - 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検証のパターン
検証に優れるのが、先読みです。同じ開始位置から、各先読みが 1 ルールを確認します。「パスワードは大文字、数字、特殊文字を持つべき」のような複合ルールを強制するため、開始(^)に複数の先読みを積み重ねましょう。その後、メインのパターンが文字列全体に一致します。
# 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+)です。幅ゼロであるのが、lookaround です。カーソルを消費せず進めません。内部のキャプチャグループは、キャプチャ DO します。
# 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置換
基本の置換
言語により異なるのが、置換の構文です:JS が string.replace(regex, str) を、Python が re.sub(pattern, repl, string) を、Java が String.replaceAll を、PHP が preg_replace を使います。すべてのマッチを置き換えるには、グローバルフラグ(g)を使いましょう。さもなければ、最初だけが置き換えられます。
# 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!"キャプチャグループの置換
置換でキャプチャグループを参照しましょう:$1、$2 が、JS/Java で、\1、\2 か(推奨される)\g<1> が、Python で、$1 か \1 が、PHP で許されます。一致全体のためには、$&(JS)/ $0(Java)/ \g<0>(Python)を使いましょう。JS の置換でリテラルの $ を置くには、$$ を。
# 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"名前付きグループの置換
置換での名前付きグループ:$<name> を使うのが JS で、\g<name> を使うのが Python、${name} を使うのが、Java/.NET です。置換での名前付き参照を PHP がサポートしないため — 番号付き($1、$2)を使いましょう。多くのグループを持つ複雑なパターンでは、名前付きの置換がはるかに読みやすいです。
# 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"すべての出現の置換
異なるのが、置換全部のセマンティクスです:/g フラグ(か replaceAll)を JS が要求する一方、デフォルトですべてを行うのが、Python の re.sub です(最初だけには count= を)。正規表現/すべてが、Java の replaceAll で、リテラル/すべてが、replace です。デフォルトですべてを行うのが、PHP の preg_replace です($limit を)。あなたの置換が最初だけかすべてかを、必ず確認しましょう。
# 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"関数の置換
動的な変換を可能にするのが、関数の置換です:大文字小文字の変換、算術、ルックアップ。(match、groups、offset、string)を関数へ渡すのが、JS です。match オブジェクトを渡すのが、Python です。キャプチャへのアクセスには、.group(n) を使いましょう。Matcher.appendReplacement を使うのが、Java で、preg_replace_callback を使うのが、PHP です。
# 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)、機密データのマスキング、数値/電話の整形、メタ文字のエスケープです。きれいで宣言的な変換のために、各々が、キャプチャグループと置換の参照を使います。
# 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"フラグ
グローバル g
最初だけでなく ALL のマッチ上で match() と replace() が機能するのが、(JS の)g フラグです。注意:lastIndex 経由で正規表現がステートフルになるのが、g です。exec() の呼び出しをまたいで同じ正規表現オブジェクトを再利用すると、バグを引き起こし得ます。より安全な反復のためには、matchAll(ES2020+)を使いましょう。re.findall / re.finditer を使うのが、Python で、replaceAll が、Java です。
# 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 タグ、email、大文字小文字を区別しない検索でよくあります。
# 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 が影響し「ません」 — それが(dotall の)s フラグの仕事です。
# 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 .Dotall s
改行にも . が一致するのが、s フラグ(dotAll)です。JS の ES2018+、Python の re.DOTALL/re.S、Java の Pattern.DOTALL です。混乱しやすいのは、「Singleline」と呼ぶのが、.NET だということです。(マルチラインの)m フラグと独立であるため、両方を使えます。/s なしの移植可能な代替:改行を含む任意の文字に一致させるには、[\s\S] か [\d\D] を。
# 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"Unicode u
パターンを Unicode の符号点として扱うのが、(JS の ES6+ の)u フラグで、サロゲートペアの問題を修正し、\p{...} のプロパティのエスケープを可能にします。デフォルトで Unicode であるのが、Python 3 です(制限には re.ASCII を)。UTF-8 のために /u を使うのが、PHP です。/u なしでは、JS が UTF-16 のコード単位に一致するため — 絵文字/CJK の処理が壊れます。
# 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("😂😂") # trueSticky の y と拡張の x
正確に lastIndex で一致するのが、(JS 専用の)sticky のフラグ y です。パーサー/トークナイザに有用です。エスケープされていない空白を無視し # をコメントの開始として扱うのが、拡張のフラグ x で、複数行にわたって文書化されたパターンが可能になります。re.VERBOSE を使うのが、Python で、/x を使うのが、PHP/PCRE、インラインの形式が、(?x) です。
# 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よくあるパターン
悪名多く難しいのが、email の正規表現です。フルの RFC 5322 の正規表現が巨大です。よくある無効なケースを捉える、簡略化されたパターンを使うのが、ほとんどの本番コードです。唯一の本物の検証が、確認リンク付きの email の送信です。明らかに悪い形式は拒否しつつ、端のケースには寛容に。
# 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
(https?://... の)単純から、RFC 準拠の複雑まであり得るのが、URL の正規表現です。本番には、組み込みの URL クラス(JS)か urllib.parse(Python)を推奨しましょう。正規表現を使うときは、フルのパースのために、scheme/host/port/path/query/fragment を別々に取り込みましょう。ドメインの正規表現:最大 63 文字のラベル、2+ 文字の TLD です。
# 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/ライブラリの方が信頼できます。
# 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 アドレス
オクテットごとに 0〜255 を強制するため、選択を使うのが、IPv4 の正規表現です: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)を使いましょう。
# 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\.)Hex の色
# に続く 3 か 6 の hex 桁であるのが、hex の色の正規表現です。注意して {3,6} を使いましょう(4、5 も許してしまいます)。より良いのが、正確に 3 か 6 を強制する、(?:[0-9a-fA-F]{3}){1,2} です。8 桁(RGBA)のサポートのためには、[0-9a-fA-F]{3,4} か {8} を使いましょう。CSS の色が、hsl()、rgb()、名前付きでもあり得るため — 本番には、CSS パーサーを使いましょう。
# 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 が、米国の ZIP です。文字-数字-文字 スペース 数字-文字-数字が、カナダです。複雑なのが、英国の郵便番号です。国の公式の形式に対して検証しましょう。マルチ国のアプリのためには、1 つの巨大パターンでなく、国ごとの正規表現を選びましょう。
# 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")パスワードの検証
最小の長さ
最重要のパスワードのルールが、最小の長さです。最低でも 8 文字を推奨し、より長いパスフレーズ(12〜16+)を促すのが、(NIST の)モダンなガイダンスです。複合ルールのためには、先読みと組み合わせましょう。長さを断言し消費しないため、他のルールが先頭からも確認できるのが、先読みの (?=.{8,}$) です。
# 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}) です。Unicode の大文字(ギリシャ、キリルなど)のためには、(JS の)u フラグ付きで \p{Lu} をか、regex モジュールを(Python)使いましょう。先読みがなければ、きれいなコードのために、別々にテスト/カウントしましょう。
# 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}) です。デフォルトのモードで Unicode の数字に一致するのが、\d です。ASCII 専用には [0-9] を使いましょう。先読みを積み重ねるより、別々の test() の呼び出しがより明快だと感じる人も多くいます。各ルールを単一の真偽の確認として読むのです。
# 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]) により特殊文字を要求しましょう。注意:特殊として数えられるのが、スペースです。必要なら、ホワイトリスト付きで明示的に除外しましょう。安全な許可リストへ制限するのが、多くのサイトです(例:[!@#$%^&*])。禁じたいなら、空白を必ず別々に確認しましょう。
# 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);組み合わせの検証
複合ルールのためには、開始に先読みを積み重ねましょう。同じ位置から、各先読みが 1 条件を断言します。保守性のためには、1 つの巨大な正規表現より、別々の test() の呼び出しが、より明快かもしれません。NIST のモダンなガイダンス:長さ(12+)を優先し、すべての印刷可能な文字を許し、既知の漏洩パスワードと照合しましょう。
# 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)日付のマッチング
YYYY-MM-DD
形式を(01〜12 の月、01〜31 の日付きの YYYY-MM-DD で)検証できるのが、正規表現ですが、意味的な妥当性を(2 月 30 日、閏年)検証できません。本物の検証のためには、Date(JS)か datetime(Python)を使いましょう。さらなる処理のために、年/月/日を取り出せるのが、キャプチャグループです。曖昧さのない日付のためには、ISO 8601 の形式を。
# 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 # invalidDD/MM/YYYY
同一に見えるのが、(ヨーロッパの)DD/MM/YYYY と、(米国の)MM/DD/YYYY です。本物の問題が、曖昧さです。保存/交換のためには、必ず ISO 8601(YYYY-MM-DD)を使いましょう。再整形できるよう、日/月/年を取り込むのが、正規表現です。本物の検証(2 月 29 日、閏年、月の長さ)には、日付ライブラリが要ります。
# 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 の HH(12 時間制なら 01〜12)、00〜59 の MM/SS です。時間のためには、選択の([01]\d|2[0-3])を使いましょう。保存のためには、必ず ISO 8601 を使いましょう(省略可能なタイムゾーン付きの HH:MM:SS です)。本物の時刻の算術には、Date/datetime を — 正規表現が検証するのは、形式だけです。
# 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 の DateTime
国際標準の、日付/時刻のためのものが、ISO 8601 です:省略可能な小数秒とタイムゾーン(UTC の Z、か ±HH:MM)付きの YYYY-MM-DDTHH:MM:SS です。本番のパースには、Date(JS)か datetime.fromisoformat(Python 3.7+)を使いましょう。形式の検証のためだけにあるのが、正規表現です。
# 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 起点の月です)。
# 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数値のマッチング
整数
整数の正規表現:^[+-]?\d+$ です(符号は省略可能です)。千の区切りのためには、3 のグループを強制するのが、^\d{1,3}(?:,\d{3})*$ です。ドット/スペースを区切りとして使うのが、ヨーロッパの形式です。0x/0o/0b の接頭辞を使うのが、hex/octal/binary です(古い言語では、octal に 0 が単独)。
# 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})。
# 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)を使うか、マイナスの前に空白を要求しましょう。
# 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)を使いましょう — ネイティブに科学表記を扱います。必要なら、仮数と指数に別々にアクセスできるのが、キャプチャグループです。
# 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 が、米国で、1.234,56 € が、EU、¥1,234 が、日本です(小数なし)。表示の整形には、toLocaleString を使いましょう。パースのためには、parseFloat の前に、通貨記号と区切りを剥ぎ取りましょう。形式を検証するのが、正規表現で、本番の通貨の整形には、Intl.NumberFormat を。
# 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)$文字列の置換
単純な置換
言語により異なるのが、最初かすべてかです。/g なしで最初だけを行うのが、JS の replace() です。デフォルトですべてを行うのが(最初には count=1 を)、Python の re.sub です。最初のための replaceFirst と、すべて正規表現のための replaceAll、すべてリテラルのための replace が、Java です。デフォルトですべてを行うのが、PHP の preg_replace です。パターンに一致させるときは正規表現を、固定テキストを置き換えるときはリテラルの文字列の置換を。
# 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"すべての置換
すべての置換の挙動:正規表現付きの /g フラグか、文字列での replaceAll を JS が必要とします。デフォルトですべてを置き換えるのが、Python の re.sub と str.replace の両方です。すべてを、replaceAll(正規表現)と replace(リテラル)が、Java の両方行います。すべてを行うのが、PHP の preg_replace です。制限するには、(Python の)count か(PHP の)$limit を。
# 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"置換でのキャプチャグループ
置換で取り込まれたグループを参照しましょう:$1、$2(と一致全体のための $&)が、JS/Java で、\1、\2 か(推奨され、\10+ との曖昧さを避ける)\g<1> が、Python で、$1 か \1 が、PHP で許されます。全体の一致のためには、$&(JS)/ $0(Java)/ \g<0>(Python)を使いましょう。JS では、リテラルの $ は $$ としてエスケープしましょう。
# 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"大文字小文字の変換
正規表現 + 関数の置換経由の大文字小文字の変換:各単語を大文字にする title case と、camelCase↔snake_case↔kebab-case の変換が、キャプチャグループと toUpperCase/toLowerCase を使います。同じ効果のための lambda 関数を使うのが、Python です。case スタイルの変換の鍵が、置換の前に取り込まれた、([A-Z]) のパターンです。
# 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)を使いましょう。
# 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 lineHTML タグの除去
/<[^>]+>/g で HTML タグを剥ぎ取りましょう(素朴ですが、単純なケースには機能します)。内容と共に <script>/<style> を取り除くには、遅延の [\s\S]*? を。本物の HTML のためには、パーサーを使いましょう(JS の DOM、Python の BeautifulSoup)— ネストしたタグ、> を持つ属性、不正な HTML では、正規表現が失敗します。エンティティのデコードには、DOM か html.unescape(Python)を。
# 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&T".replace(/&/g, "&")
"<tag>".replace(/</g, "<").replace(/>/g, ">")
" ".replace(/ /g, " ")
""".replace(/"/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.抽出と分割
最初の一致の抽出
最初の一致の抽出:配列(か null)を返すのが、JS の String.match() で、Match オブジェクト(か None)を返すのが、Python の re.search、次の一致へ進むのが、Java の Matcher.find()、グループ付きで配列を満たすのが、PHP の preg_match です。パターンがどこにでもあり得るなら、(Python の)search を使うしましょう — 開始にアンカーするのが、match です。
# 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すべての一致の抽出
すべての一致の抽出:(グループの詳細なしで)マッチのフラットな配列を返すのが、/g 付きの JS の match() で、完全な情報付きのイテレータを返すのが、matchAll(ES2020+)です。グループ(かグループがなければ一致全体)のリストを返すのが、Python の re.findall です。大きなテキスト上の遅延反復のためには、re.finditer を。
# 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)文字列の分割
正規表現による文字列の分割:String.split(regex) が、JS で、re.split が、Python、String.split が、Java、preg_split が、PHP、regexp.Split が、Go です。結果の配列に区切りを残すのが、パターン内のキャプチャグループです。分割数に上限を設けるのが、limit/maxsplit です。空白の分割:複数のスペース、タブ、改行を、/\s+/ が扱います。
# 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 のペアを取り出しましょう。きれいなオブジェクトを構築するのが、(JS の)Object.fromEntries + matchAll か、(Python の)dict + findall です。本物の URL のクエリ文字列と HTTP ヘッダーのためには、組み込みの URL/URLSearchParams(JS)か urllib.parse(Python)を推奨しましょう — 正しく URL エンコーディングを扱うからです。
# 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+)、数値、文字列、演算子、句読点です。トークナイザのパターンのためには、キャプチャグループ付きの選択を使いましょう。位置付きの match オブジェクトを与えるのが、Python の re.finditer です。本物の NLP のトークン化のためには、NLTK や spaCy のようなライブラリを使いましょう — 正規表現が扱えない端のケースを扱うからです。
# 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貪欲対遅延
貪欲なデフォルト
可能な限り多く一致し、その後、パターンの残りが成功できるようバックトラックするのが、貪欲な量指定子です。これが、HTML のような予想外の一致をしばしば引き起こします。1 つのものとして、<b>...</b><i>...</i> の全体に一致するのが、<.+> です。これを避けるには、遅延の量指定子か具体的な文字クラスを。