正規表現テスター
正規表現をテスト文字列に対して実行し、すべてのマッチ箇所をハイライト表示で確認できます
パターン
テスト文字列
正規表現とは?
正規表現(regex または regexp)は、検索パターンを定義する文字の並びです。正規表現テスターを使うと、パターンを記述してサンプルテキストに対して実行し、すべてのマッチ箇所をリアルタイムでハイライト表示できます。この概念は1950年代に数学者 Stephen Kleene が正規言語について研究したことに端を発し、1968年には Ken Thompson が QED テキストエディタに初めての正規表現エンジンを組み込みました。
正規表現エンジンはパターンを左から右に読み進め、マッチを試みながら入力文字を消費します。部分マッチが失敗した場合はバックトラッキングを行い、エンジンは一歩戻ってパターン内の別の経路を試みます。Go で使われている RE2 のように、バックトラッキングを一切行わないエンジンもあります。RE2 はパターンを決定性有限オートマトン(DFA)に変換することで線形時間のマッチングを保証しますが、その代わり後方参照などの機能はサポートしていません。
正規表現の構文は緩やかに標準化されています。最も広く使われているのは PCRE(Perl Compatible Regular Expressions)で、PHP、Python の re モジュール、JavaScript が細かな違いはありながらもこれをサポートしています。POSIX はより制限された構文を定義しており、grep や sed で使われています。言語間でパターンを移植する際にはこの違いが重要です。JavaScript で動作する先読みアサーションが、Go の RE2 エンジンではまったくコンパイルできない場合もあります。
オンライン正規表現テスターを使う理由
コードファイルで正規表現を書くと、パターンを修正するたびに保存・実行・結果確認が必要です。ブラウザベースの正規表現テスターはそのフィードバックループをゼロに縮めます。入力した瞬間にマッチが見えます。
正規表現テスターの活用シーン
正規表現構文クイックリファレンス
以下の表は最もよく使われる正規表現トークンをまとめています。JavaScript、Python、Go、PHP、および PCRE 互換エンジンの大部分で動作します。言語固有の拡張(Python の条件パターンや \k 構文を使った JavaScript の名前付きグループなど)はコード例のセクションで説明しています。
| パターン | 名前 | 説明 |
|---|---|---|
| . | Any character | Matches any single character except newline (unless s flag is set) |
| \d | Digit | Matches [0-9] |
| \w | Word character | Matches [a-zA-Z0-9_] |
| \s | Whitespace | Matches space, tab, newline, carriage return, form feed |
| \b | Word boundary | Matches the position between a word character and a non-word character |
| ^ | Start of string/line | Matches the start of the input; with m flag, matches start of each line |
| $ | End of string/line | Matches the end of the input; with m flag, matches end of each line |
| * | Zero or more | Matches the preceding token 0 or more times (greedy) |
| + | One or more | Matches the preceding token 1 or more times (greedy) |
| ? | Optional | Matches the preceding token 0 or 1 time |
| {n,m} | Quantifier range | Matches the preceding token between n and m times |
| () | Capturing group | Groups tokens and captures the matched text for back-references |
| (?:) | Non-capturing group | Groups tokens without capturing the matched text |
| (?=) | Positive lookahead | Matches a position followed by the given pattern, without consuming it |
| (?<=) | Positive lookbehind | Matches a position preceded by the given pattern, without consuming it |
| [abc] | Character class | Matches any one of the characters inside the brackets |
| [^abc] | Negated class | Matches any character not inside the brackets |
| | | Alternation | Matches the expression before or after the pipe |
正規表現フラグの解説
フラグ(モディファイアとも呼ばれます)はエンジンがパターンを処理する方法を変更します。JavaScript では閉じスラッシュの後に付加します: /pattern/gi。Python では第2引数として渡します: re.findall(pattern, text, re.IGNORECASE | re.MULTILINE)。すべてのフラグがすべての言語で使えるわけではありません。
| フラグ | 名前 | 動作 |
|---|---|---|
| g | Global | Find all matches, not just the first one |
| i | Case-insensitive | Letters match both uppercase and lowercase |
| m | Multiline | ^ and $ match start/end of each line, not just the whole string |
| s | Dot-all | . matches newline characters as well |
| u | Unicode | Treat the pattern and subject as a Unicode string; enables \u{FFFF} syntax |
| y | Sticky | Matches only from the lastIndex position in the target string |
コード例
JavaScript、Python、Go、コマンドラインでの正規表現の実用例です。各例ではパターンの構築、マッチの抽出、出力を示しています。
// Match all email addresses in a string
const text = 'Contact us at support@example.com or sales@example.com'
const emailRegex = /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g
const matches = text.matchAll(emailRegex)
for (const match of matches) {
console.log(match[0], 'at index', match.index)
}
// → "support@example.com" at index 14
// → "sales@example.com" at index 37
// Named capture groups (ES2018+)
const dateRegex = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/
const result = '2026-03-30'.match(dateRegex)
console.log(result.groups)
// → { year: "2026", month: "03", day: "30" }
// Replace with a callback
'hello world'.replace(/\b\w/g, c => c.toUpperCase())
// → "Hello World"import re
# Find all IPv4 addresses
text = 'Server 192.168.1.1 responded, fallback to 10.0.0.255'
pattern = r'\b(?:\d{1,3}\.){3}\d{1,3}\b'
matches = re.findall(pattern, text)
print(matches) # → ['192.168.1.1', '10.0.0.255']
# Named groups and match objects
date_pattern = r'(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})'
m = re.search(date_pattern, 'Released on 2026-03-30')
if m:
print(m.group('year')) # → '2026'
print(m.group('month')) # → '03'
# Compile for repeated use (faster in loops)
compiled = re.compile(r'\b[A-Z][a-z]+\b')
words = compiled.findall('Hello World Foo bar')
print(words) # → ['Hello', 'World', 'Foo']package main
import (
"fmt"
"regexp"
)
func main() {
// Find all matches
re := regexp.MustCompile(`\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}\b`)
text := "Contact support@example.com or sales@example.com"
matches := re.FindAllString(text, -1)
fmt.Println(matches)
// → [support@example.com sales@example.com]
// Named capture groups
dateRe := regexp.MustCompile(`(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})`)
match := dateRe.FindStringSubmatch("2026-03-30")
for i, name := range dateRe.SubexpNames() {
if name != "" {
fmt.Printf("%s: %s\n", name, match[i])
}
}
// → year: 2026
// → month: 03
// → day: 30
// Replace with a function
result := re.ReplaceAllStringFunc(text, func(s string) string {
return "[REDACTED]"
})
fmt.Println(result)
// → Contact [REDACTED] or [REDACTED]
}# Find lines matching an IP address pattern
grep -E '\b([0-9]{1,3}\.){3}[0-9]{1,3}\b' access.log
# Extract email addresses from a file
grep -oE '[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}' contacts.txt
# Replace dates from YYYY-MM-DD to DD/MM/YYYY using sed
echo "2026-03-30" | sed -E 's/([0-9]{4})-([0-9]{2})-([0-9]{2})/\3\/\2\/\1/'
# → 30/03/2026
# Count matches per file in a directory
grep -rcE 'TODO|FIXME|HACK' src/
# → src/main.js:3
# → src/utils.js:1