jpskill.com
💬 コミュニケーション コミュニティ

pattern-detection

コードやデータの中から、よくない兆候やセキュリティ上の弱点、繰り返されるパターンなどを、正規表現や統計分析を使って見つけ出し、問題解決や改善につなげるSkill。

📜 元の英語説明(参考)

Detect patterns, anomalies, and trends in code and data. Use when identifying code smells, finding security vulnerabilities, or discovering recurring patterns. Handles regex patterns, AST analysis, and statistical anomaly detection.

🇯🇵 日本人クリエイター向け解説

一言でいうと

コードやデータの中から、よくない兆候やセキュリティ上の弱点、繰り返されるパターンなどを、正規表現や統計分析を使って見つけ出し、問題解決や改善につなげるSkill。

※ jpskill.com 編集部が日本のビジネス現場向けに補足した解説です。Skill本体の挙動とは独立した参考情報です。

⚡ おすすめ: コマンド1行でインストール(60秒)

下記のコマンドをコピーしてターミナル(Mac/Linux)または PowerShell(Windows)に貼り付けてください。 ダウンロード → 解凍 → 配置まで全自動。

🍎 Mac / 🐧 Linux
mkdir -p ~/.claude/skills && cd ~/.claude/skills && curl -L -o pattern-detection.zip https://jpskill.com/download/20914.zip && unzip -o pattern-detection.zip && rm pattern-detection.zip
🪟 Windows (PowerShell)
$d = "$env:USERPROFILE\.claude\skills"; ni -Force -ItemType Directory $d | Out-Null; iwr https://jpskill.com/download/20914.zip -OutFile "$d\pattern-detection.zip"; Expand-Archive "$d\pattern-detection.zip" -DestinationPath $d -Force; ri "$d\pattern-detection.zip"

完了後、Claude Code を再起動 → 普通に「動画プロンプト作って」のように話しかけるだけで自動発動します。

💾 手動でダウンロードしたい(コマンドが難しい人向け)
  1. 1. 下の青いボタンを押して pattern-detection.zip をダウンロード
  2. 2. ZIPファイルをダブルクリックで解凍 → pattern-detection フォルダができる
  3. 3. そのフォルダを C:\Users\あなたの名前\.claude\skills\(Win)または ~/.claude/skills/(Mac)へ移動
  4. 4. Claude Code を再起動

⚠️ ダウンロード・利用は自己責任でお願いします。当サイトは内容・動作・安全性について責任を負いません。

🎯 このSkillでできること

下記の説明文を読むと、このSkillがあなたに何をしてくれるかが分かります。Claudeにこの分野の依頼をすると、自動で発動します。

📦 インストール方法 (3ステップ)

  1. 1. 上の「ダウンロード」ボタンを押して .skill ファイルを取得
  2. 2. ファイル名の拡張子を .skill から .zip に変えて展開(macは自動展開可)
  3. 3. 展開してできたフォルダを、ホームフォルダの .claude/skills/ に置く
    • · macOS / Linux: ~/.claude/skills/
    • · Windows: %USERPROFILE%\.claude\skills\

Claude Code を再起動すれば完了。「このSkillを使って…」と話しかけなくても、関連する依頼で自動的に呼び出されます。

詳しい使い方ガイドを見る →
最終更新
2026-05-18
取得日時
2026-05-18
同梱ファイル
1

📖 Skill本文(日本語訳)

※ 原文(英語/中国語)を Gemini で日本語化したものです。Claude 自身は原文を読みます。誤訳がある場合は原文をご確認ください。

[スキル名] pattern-detection

パターン検出

このスキルを使用する場面

  • コードレビュー: 問題のあるパターンを事前に検出します。
  • セキュリティレビュー: 脆弱性パターンをスキャンします。
  • リファクタリング: 重複するコードを特定します。
  • モニタリング: 異常を警告します。

手順

ステップ1: コードの不吉な匂いパターンを検出する

長い関数を検出する:

# Find functions with 50+ lines
grep -n "function\|def\|func " **/*.{js,ts,py,go} | \
  while read line; do
    file=$(echo $line | cut -d: -f1)
    linenum=$(echo $line | cut -d: -f2)
    # Function length calculation logic
  done

重複コードパターン:

# Search for similar code blocks
grep -rn "if.*==.*null" --include="*.ts" .
grep -rn "try\s*{" --include="*.java" . | wc -l

マジックナンバー:

# Search for hard-coded numbers
grep -rn "[^a-zA-Z][0-9]{2,}[^a-zA-Z]" --include="*.{js,ts}" .

ステップ2: セキュリティ脆弱性パターン

SQLインジェクションのリスク:

# SQL query built via string concatenation
grep -rn "query.*+.*\$\|execute.*%s\|query.*f\"" --include="*.py" .
grep -rn "SELECT.*\+.*\|\|" --include="*.{js,ts}" .

ハードコードされたシークレット:

# Password, API key patterns
grep -riE "(password|secret|api_key|apikey)\s*=\s*['\"][^'\"]+['\"]" --include="*.{js,ts,py,java}" .

# AWS key patterns
grep -rE "AKIA[0-9A-Z]{16}" .

危険な関数の使用:

# eval, exec usage
grep -rn "eval\(.*\)\|exec\(.*\)" --include="*.{py,js}" .

# innerHTML usage
grep -rn "innerHTML\s*=" --include="*.{js,ts}" .

ステップ3: コード構造パターン

インポート分析:

# Candidates for unused imports
grep -rn "^import\|^from.*import" --include="*.py" . | \
  awk -F: '{print $3}' | sort | uniq -c | sort -rn

TODO/FIXMEパターン:

# Find unfinished code
grep -rn "TODO\|FIXME\|HACK\|XXX" --include="*.{js,ts,py}" .

エラー処理パターン:

# Empty catch blocks
grep -rn "catch.*{[\s]*}" --include="*.{js,ts,java}" .

# Ignored errors
grep -rn "except:\s*pass" --include="*.py" .

ステップ4: データ異常パターン

正規表現パターン:

import re

patterns = {
    'email': r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}',
    'phone': r'\d{3}[-.\s]?\d{4}[-.\s]?\d{4}',
    'ip_address': r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}',
    'credit_card': r'\d{4}[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{4}',
    'ssn': r'\d{3}-\d{2}-\d{4}',
}

def detect_sensitive_data(text):
    found = {}
    for name, pattern in patterns.items():
        matches = re.findall(pattern, text)
        if matches:
            found[name] = len(matches)
    return found

統計的異常検出:

import numpy as np
from scipy import stats

def detect_anomalies_zscore(data, threshold=3):
    """Z-score-based outlier detection"""
    z_scores = np.abs(stats.zscore(data))
    return np.where(z_scores > threshold)[0]

def detect_anomalies_iqr(data, k=1.5):
    """IQR-based outlier detection"""
    q1, q3 = np.percentile(data, [25, 75])
    iqr = q3 - q1
    lower = q1 - k * iqr
    upper = q3 + k * iqr
    return np.where((data < lower) | (data > upper))[0]

ステップ5: トレンド分析

import pandas as pd

def analyze_trend(df, date_col, value_col):
    """Time-series trend analysis"""
    df[date_col] = pd.to_datetime(df[date_col])
    df = df.sort_values(date_col)

    # Moving averages
    df['ma_7'] = df[value_col].rolling(window=7).mean()
    df['ma_30'] = df[value_col].rolling(window=30).mean()

    # Growth rate
    df['growth'] = df[value_col].pct_change() * 100

    # Trend direction
    recent_trend = df['ma_7'].iloc[-1] > df['ma_30'].iloc[-1]

    return {
        'trend_direction': 'up' if recent_trend else 'down',
        'avg_growth': df['growth'].mean(),
        'volatility': df[value_col].std()
    }

出力形式

パターン検出レポート

# Pattern Detection Report

## Summary
- Files scanned: XXX
- Patterns detected: XX
- High severity: X
- Medium severity: X
- Low severity: X

## Detected patterns

### Security vulnerabilities (HIGH)
| File | Line | Pattern | Description |
|------|------|------|------|
| file.js | 42 | hardcoded-secret | Hard-coded API key |

### Code smells (MEDIUM)
| File | Line | Pattern | Description |
|------|------|------|------|
| util.py | 100 | long-function | Function length: 150 lines |

## Recommended actions
1. [Action 1]
2. [Action 2]

ベストプラクティス

  1. 増分分析: シンプルなパターンから始めます。
  2. 誤検知の最小化: 正確な正規表現を使用します。
  3. コンテキストの確認: マッチ周辺のコンテキストを理解します。
  4. 優先順位付け: 重大度でソートします。

制約

必須ルール (MUST)

  1. 読み取り専用操作であること
  2. 結果の検証を行うこと
  3. 誤検知の可能性を明記すること

禁止事項 (MUST NOT)

  1. コードを自動修正しないこと
  2. 機密情報をログに記録しないこと

参考文献

例1: 基本的な使用法

<!-- ここに例のコンテンツを追加してください -->

例2: 高度な使用法

<!-- ここに高度な例のコンテンツを追加してください -->

📜 原文 SKILL.md(Claudeが読む英語/中国語)を展開

Pattern Detection

When to use this skill

  • Code review: Proactively detect problematic patterns
  • Security review: Scan for vulnerability patterns
  • Refactoring: Identify duplicate code
  • Monitoring: Alert on anomalies

Instructions

Step 1: Detect code smell patterns

Detect long functions:

# Find functions with 50+ lines
grep -n "function\|def\|func " **/*.{js,ts,py,go} | \
  while read line; do
    file=$(echo $line | cut -d: -f1)
    linenum=$(echo $line | cut -d: -f2)
    # Function length calculation logic
  done

Duplicate code patterns:

# Search for similar code blocks
grep -rn "if.*==.*null" --include="*.ts" .
grep -rn "try\s*{" --include="*.java" . | wc -l

Magic numbers:

# Search for hard-coded numbers
grep -rn "[^a-zA-Z][0-9]{2,}[^a-zA-Z]" --include="*.{js,ts}" .

Step 2: Security vulnerability patterns

SQL Injection risks:

# SQL query built via string concatenation
grep -rn "query.*+.*\$\|execute.*%s\|query.*f\"" --include="*.py" .
grep -rn "SELECT.*\+.*\|\|" --include="*.{js,ts}" .

Hard-coded secrets:

# Password, API key patterns
grep -riE "(password|secret|api_key|apikey)\s*=\s*['\"][^'\"]+['\"]" --include="*.{js,ts,py,java}" .

# AWS key patterns
grep -rE "AKIA[0-9A-Z]{16}" .

Dangerous function usage:

# eval, exec usage
grep -rn "eval\(.*\)\|exec\(.*\)" --include="*.{py,js}" .

# innerHTML usage
grep -rn "innerHTML\s*=" --include="*.{js,ts}" .

Step 3: Code structure patterns

Import analysis:

# Candidates for unused imports
grep -rn "^import\|^from.*import" --include="*.py" . | \
  awk -F: '{print $3}' | sort | uniq -c | sort -rn

TODO/FIXME patterns:

# Find unfinished code
grep -rn "TODO\|FIXME\|HACK\|XXX" --include="*.{js,ts,py}" .

Error handling patterns:

# Empty catch blocks
grep -rn "catch.*{[\s]*}" --include="*.{js,ts,java}" .

# Ignored errors
grep -rn "except:\s*pass" --include="*.py" .

Step 4: Data anomaly patterns

Regex patterns:

import re

patterns = {
    'email': r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}',
    'phone': r'\d{3}[-.\s]?\d{4}[-.\s]?\d{4}',
    'ip_address': r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}',
    'credit_card': r'\d{4}[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{4}',
    'ssn': r'\d{3}-\d{2}-\d{4}',
}

def detect_sensitive_data(text):
    found = {}
    for name, pattern in patterns.items():
        matches = re.findall(pattern, text)
        if matches:
            found[name] = len(matches)
    return found

Statistical anomaly detection:

import numpy as np
from scipy import stats

def detect_anomalies_zscore(data, threshold=3):
    """Z-score-based outlier detection"""
    z_scores = np.abs(stats.zscore(data))
    return np.where(z_scores > threshold)[0]

def detect_anomalies_iqr(data, k=1.5):
    """IQR-based outlier detection"""
    q1, q3 = np.percentile(data, [25, 75])
    iqr = q3 - q1
    lower = q1 - k * iqr
    upper = q3 + k * iqr
    return np.where((data < lower) | (data > upper))[0]

Step 5: Trend analysis

import pandas as pd

def analyze_trend(df, date_col, value_col):
    """Time-series trend analysis"""
    df[date_col] = pd.to_datetime(df[date_col])
    df = df.sort_values(date_col)

    # Moving averages
    df['ma_7'] = df[value_col].rolling(window=7).mean()
    df['ma_30'] = df[value_col].rolling(window=30).mean()

    # Growth rate
    df['growth'] = df[value_col].pct_change() * 100

    # Trend direction
    recent_trend = df['ma_7'].iloc[-1] > df['ma_30'].iloc[-1]

    return {
        'trend_direction': 'up' if recent_trend else 'down',
        'avg_growth': df['growth'].mean(),
        'volatility': df[value_col].std()
    }

Output format

Pattern detection report

# Pattern Detection Report

## Summary
- Files scanned: XXX
- Patterns detected: XX
- High severity: X
- Medium severity: X
- Low severity: X

## Detected patterns

### Security vulnerabilities (HIGH)
| File | Line | Pattern | Description |
|------|------|------|------|
| file.js | 42 | hardcoded-secret | Hard-coded API key |

### Code smells (MEDIUM)
| File | Line | Pattern | Description |
|------|------|------|------|
| util.py | 100 | long-function | Function length: 150 lines |

## Recommended actions
1. [Action 1]
2. [Action 2]

Best practices

  1. Incremental analysis: Start with simple patterns
  2. Minimize false positives: Use precise regex
  3. Check context: Understand the context around a match
  4. Prioritize: Sort by severity

Constraints

Required rules (MUST)

  1. Read-only operation
  2. Perform result verification
  3. State the possibility of false positives

Prohibited (MUST NOT)

  1. Do not auto-modify code
  2. Do not log sensitive information

References

Examples

Example 1: Basic usage

<!-- Add example content here -->

Example 2: Advanced usage

<!-- Add advanced example content here -->