regex-tester について
regex-tester は、正規表現のテスト、デバッグ、理解を支援するツールです。例からのパターン生成に加え、置換と構文の検証にも対応します。
主な機能
- 01パターンをテストして一致結果を確認
- 02一致した文字列と位置を可視化
- 03パターンを平易な英語で説明
- 04例からパターンを生成
- 05検索と置換をテスト
- 06構文を検証し、一般的なパターンを利用
活用シーン
- 01テキスト処理用の正規表現をデバッグ
- 02テキストやファイル内の一致箇所を確認
- 03サンプル文字列からパターンを生成
- 04電話番号の検証と形式変換
インストール
コマンドをコピーしてターミナルで実行します。
$
npx skills add https:/ / github.com/ dkyazzentwatwa/ chatgpt-skills --skill regex-testerインストール後、Claude Code で/regex-testerを入力して読み込まれたか確認します。
同梱ファイルscripts/regex_tester.pyscripts/requirements.txt
詳細
正規表現テスター
詳細なマッチ表示、平易な言葉による解説、サンプルからのパターン生成を使って、正規表現をテストおよびデバッグします。
クイックスタート
from scripts.regex_tester import RegexTester
# Test pattern
tester = RegexTester()
result = tester.test(r"\d{3}-\d{4}", "Call 555-1234 today")
print(result['matches']) # ['555-1234']
# Explain pattern
explanation = tester.explain(r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b")
print(explanation)
# Generate pattern from examples
pattern = tester.generate_pattern(["555-1234", "123-4567", "999-0000"])
print(pattern) # r"\d{3}-\d{4}"
機能
- パターンのテスト:テキストに対してテストし、詳細な結果を確認できます
- マッチの表示:マッチした箇所と位置を正確に確認できます
- パターンの解説:正規表現を平易な言葉で解説します
- パターンの生成:マッチ例からパターンを作成します
- 検索と置換:置換パターンをテストします
- 一般的なパターン:事前に用意されたパターンのライブラリです
- 検証:使用前にパターンの構文を確認します
API リファレンス
テスト
tester = RegexTester()
# Basic test
result = tester.test(r"\d+", "There are 42 items")
# {
# 'pattern': r'\d+',
# 'text': 'There are 42 items',
# 'matches': ['42'],
# 'match_count': 1,
# 'positions': [(10, 12)], # (start, end)
# 'groups': []
# }
# With flags
result = tester.test(r"hello", "Hello World", ignore_case=True)
# All matches with groups
result = tester.test(r"(\d{3})-(\d{4})", "555-1234 and 999-0000")
# matches: ['555-1234', '999-0000']
# groups: [('555', '1234'), ('999', '0000')]
解説
explanation = tester.explain(r"\b\w+@\w+\.\w{2,}\b")
# Returns:
# \b - Word boundary
# \w+ - One or more word characters
# @ - Literal '@'
# \w+ - One or more word characters
# \. - Literal '.'
# \w{2,} - Two or more word characters
# \b - Word boundary
パターン生成
# Generate pattern from examples
examples = ["[email protected]", "[email protected]", "[email protected]"]
pattern = tester.generate_pattern(examples)
# Suggests: r"[a-z]+@[a-z]+\.(com|org|net)"
# With negative examples (what NOT to match)
pattern = tester.generate_pattern(
positive=["555-1234", "999-0000"],
negative=["555-12", "12345"]
)
検索と置換
result = tester.replace(
pattern=r"(\d{3})-(\d{4})",
replacement=r"(\1) \2",
text="Call 555-1234"
)
# "Call (555) 1234"
検証
# Check if pattern is valid
is_valid, error = tester.validate(r"[invalid")
# is_valid: False
# error: "unterminated character set"
一般的なパターン
# Get pre-built patterns
email = tester.patterns['email']
phone = tester.patterns['phone']
url = tester.patterns['url']
ip = tester.patterns['ipv4']
CLI の使い方
# Test pattern
python regex_tester.py --pattern "\d+" --text "There are 42 items"
# Test from file
python regex_tester.py --pattern "\w+@\w+\.\w+" --file emails.txt
# Explain pattern
python regex_tester.py --explain "\b[A-Z][a-z]+\b"
# Find and replace
python regex_tester.py --pattern "(\d+)" --replace "[$1]" --text "Item 42"
# Generate pattern
python regex_tester.py --generate "555-1234,999-0000,123-4567"
# Interactive mode
python regex_tester.py --interactive
CLI 引数
| 引数 | 説明 | デフォルト |
|---|---|---|
--pattern | 正規表現パターン | - |
--text | テスト対象のテキスト | - |
--file | テスト対象のファイル | - |
--explain | パターンを解説します | False |
--replace | 置換パターン | - |
--generate | サンプルから生成します | - |
--ignore-case | 大文字と小文字を区別しません | False |
--multiline | 複数行モード | False |
--interactive | 対話モード | False |
例
メールアドレスの検証
tester = RegexTester()
email_pattern = r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"
test_emails = [
"[email protected]",
"invalid.email",
"user@domain",
"[email protected]"
]
for email in test_emails:
result = tester.test(email_pattern, email)
status = "Valid" if result['matches'] else "Invalid"
print(f"{email}: {status}")
ログからデータを抽出
tester = RegexTester()
log_line = '[2024-01-15 14:30:22] ERROR: Connection timeout (192.168.1.100)'
pattern = r'\[(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})\] (\w+): (.+) \((\d+\.\d+\.\d+\.\d+)\)'
result = tester.test(pattern, log_line)
if result['groups']:
timestamp, level, message, ip = result['groups'][0]
print(f"Time: {timestamp}")
print(f"Level: {level}")
print(f"Message: {message}")
print(f"IP: {ip}")
電話番号のフォーマット
tester = RegexTester()
# Normalize various phone formats
phones = ["5551234567", "(555) 123-4567", "555.123.4567"]
pattern = r"[\(\)\.\s-]?"
for phone in phones:
# Remove all formatting
clean = tester.replace(r"[\(\)\.\s-]", "", phone)
# Format consistently
formatted = tester.replace(
r"(\d{3})(\d{3})(\d{4})",
r"(\1) \2-\3",
clean
)
print(f"{phone} -> {formatted}")
複雑なパターンを理解する
tester = RegexTester()
# Explain a complex pattern
pattern = r"(?:https?://)?(?:www\.)?([a-zA-Z0-9-]+)\.([a-zA-Z]{2,})(?:/\S*)?"
explanation = tester.explain(pattern)
print(explanation)
# (?:https?://)? - Optional non-capturing group: 'http://' or 'https://'
# (?:www\.)? - Optional non-capturing group: 'www.'
# ([a-zA-Z0-9-]+) - Capturing group 1: domain name
# \. - Literal '.'
# ([a-zA-Z]{2,}) - Capturing group 2: TLD
# (?:/\S*)? - Optional non-capturing group: path
一般的なパターンのライブラリ
| 名前 | パターン | マッチする例 |
|---|---|---|
email | 複雑 | [email protected] |
phone_us | \d{3}[-.]?\d{3}[-.]?\d{4} | 555-123-4567 |
url | 複雑 | https://example.com |
ipv4 | \d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3} | 192.168.1.1 |
date_iso | \d{4}-\d{2}-\d{2} | 2024-01-15 |
time_24h | \d{2}:\d{2}(:\d{2})? | 14:30:00 |
hex_color | #[0-9A-Fa-f]{6} | #FF5733 |
zipcode_us | \d{5}(-\d{4})? | 12345-6789 |
依存関係
(No external dependencies - uses Python standard library re module)
制限事項
- パターン生成はヒューリスティックなため、最適ではない場合があります
- 一部の高度な正規表現機能は Python 固有です
- 解説は一般的なパターンで最も効果を発揮します
- 非常に長いパターンでは、解説が簡略化される場合があります
コメント
Markdown 対応