Skill: kaiyuelv/regex-master (version 1.0.0)

# regex-master ## 技能概述 正则表达式生成、测试、解释与可视化工具集。帮助用户快速构建、验证和理解正则表达式，提供自然语言描述到正则的自动转换。 ## 何时使用 - 需要从零构建正则表达式时 - 需要解释现有正则的含义时 - 需要测试正则是否匹配目标文本时 - 需要提取文本中特定模式的数据时 ## 使用方法 ### 基础用法 ```python from scripts.regex_engine import RegexMaster rm = RegexMaster() # 测试正则是否匹配 result = rm.test("^\d{11}$", "13800138000") # -> {"match": true, "groups": []} # 解释正则含义 explanation = rm.explain("^(?=.*[A-Z])(?=.*\d).{8,}$") # -> 密码强度检查：至少8位，含大写字母和数字 # 从自然语言生成正则 pattern = rm.generate("提取中国大陆手机号") # -> "1[3-9]\\d{9}" # 在文本中提取所有匹配 matches = rm.extract_all("\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Z|a-z]{2,}\\b", text) # -> ["[REDACTED_SECRET]", "[REDACTED_SECRET]"] ``` ## 文件结构 ``` regex-master/ ├── SKILL.md ├── README.md ├── requirements.txt ├── scripts/ │ └── regex_engine.py # 核心引擎 ├── examples/ │ └── basic_usage.py # 使用示例 └── tests/ └── test_regex_master.py # 单元测试 ``` ## 依赖 - `re` (Python 内置) - 可选: `regex` 库提供更强大的正则支持 ## 标签 regex, pattern-matching, text-processing, developer-tools

path: README.md
content: # Regex Master

正则表达式大师 — 生成、测试、解释、提取一站式工具。

## Features

| 功能 | 说明 |
|------|------|
| 智能生成 | 根据自然语言描述自动生成正则表达式 |
| 在线测试 | 测试正则是否匹配目标文本，返回捕获组 |
| 语义解释 | 将复杂的正则表达式翻译成人类可读的中文说明 |
| 批量提取 | 从文本中提取所有匹配项，支持命名捕获组 |
| 常用模板 | 内置邮箱、手机号、身份证、URL等常见模式 |
| 可视化辅助 | 输出正则的结构树，帮助理解嵌套逻辑 |

## Quick Start

```python
from scripts.regex_engine import RegexMaster

rm = RegexMaster()

# 1. 测试正则
rm.test(r"^\d{4}-\d{2}-\d{2}$", "2026-04-27")
# { "match": True, "groups": [] }

# 2. 生成正则 — "匹配 IPv4 地址"
rm.generate("匹配 IPv4 地址")
# "^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$"

# 3. 解释正则
rm.explain(r"^(?=.*[A-Z])(?=.*[a-z])(?=.*\d).{8,}$")
# 密码强度检查：至少8位，包含大写字母、小写字母和数字

# 4. 批量提取
rm.extract_all(r"\b\w+@\w+\.\w+\b", "Contact: [REDACTED_SECRET], [REDACTED_SECRET]")
# ["[REDACTED_SECRET]", "[REDACTED_SECRET]"]

# 5. 常用模板
rm.get_template("email")
# "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"
```

## Templates

内置常用正则模板：

- `email` — 邮箱地址
- `phone_cn` — 中国大陆手机号
- `idcard` — 身份证号码
- `url` — URL 链接
- `ipv4` — IPv4 地址
- `date_iso` — ISO 日期格式
- `chinese_chars` — 中文字符
- `hex_color` — 十六进制颜色值
- `credit_card` — 信用卡号（简单校验）

## Installation

无需额外依赖，纯 Python 内置 `re` 模块实现。

可选安装 `regex` 库以获得更强大的引擎支持：
```bash
pip install regex
```

## License
MIT

path: examples/basic_usage.py
content: """
Regex Master - 基础使用示例
"""
from scripts.regex_engine import RegexMaster


def main():
    rm = RegexMaster()

    print("=" * 50)
    print("示例 1: 测试正则是否匹配")
    print("=" * 50)
    result = rm.test(r"^\d{11}$", "13800138000")
    print(f"测试 13800138000 匹配 ^\\d{{11}}$: {result}")

    result2 = rm.test(r"^\d{11}$", "1380013800")
    print(f"测试 1380013800 匹配 ^\\d{{11}}$: {result2}")

    print("\n" + "=" * 50)
    print("示例 2: 解释正则含义")
    print("=" * 50)
    exp = rm.explain(r"^(?=.*[A-Z])(?=.*\d).{8,}$")
    print(f"解释密码强度正则: {exp}")

    print("\n" + "=" * 50)
    print("示例 3: 从自然语言生成正则")
    print("=" * 50)
    patterns = [
        "提取中国大陆手机号",
        "匹配邮箱地址",
        "匹配 IPv4 地址",
    ]
    for desc in patterns:
        pat = rm.generate(desc)
        print(f"'{desc}' -> {pat}")

    print("\n" + "=" * 50)
    print("示例 4: 从文本中提取所有邮箱")
    print("=" * 50)
    text = """
    联系方式:
    张三: [REDACTED_SECRET]
    李四: [REDACTED_SECRET]
    王五: [REDACTED_SECRET]
    """
    emails = rm.extract_all(r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}", text)
    print(f"提取到的邮箱: {emails}")

    print("\n" + "=" * 50)
    print("示例 5: 使用内置模板")
    print("=" * 50)
    print("可用模板:", list(rm.list_templates().keys()))
    print(f"邮箱模板: {rm.get_template('email')}")
    print(f"手机号模板: {rm.get_template('phone_cn')}")

    print("\n" + "=" * 50)
    print("示例 6: 验证正则语法")
    print("=" * 50)
    valid = rm.validate_pattern(r"^[a-z]+$")
    print(f"验证 ^[a-z]+$: {valid}")
    invalid = rm.validate_pattern(r"[a-z")
    print(f"验证 [a-z: {invalid}")

    print("\n" + "=" * 50)
    print("示例 7: 正则替换")
    print("=" * 50)
    text = "我的电话是 138-1234-5678，备用 139-8765-4321"
    result = rm.replace(r"(\d{3})-(\d{4})-(\d{4})", text, r"\1****\3")
    print(f"替换后: {result}")


if __name__ == "__main__":
    main()


path: requirements.txt
content: # 无需额外依赖，纯 Python 内置模块
# 可选增强：
# regex>=2024.4.16


path: scripts/regex_engine.py
content: """
Regex Master - 正则表达式一站式工具引擎
"""
import re
from typing import List, Dict, Any, Optional, Union


class RegexMaster:
    """正则表达式生成、测试、解释与提取工具"""

    # 常用正则模板库
    TEMPLATES = {
        "email": r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$",
        "phone_cn": r"^1[3-9]\d{9}$",
        "idcard": r"^[1-9]\d{5}(?:18|19|20)\d{2}(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\d|3[01])\d{3}[\dXx]$",
        "url": r"^(https?|ftp)://[^\s/$.?#].[^\s]*$",
        "ipv4": r"^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$",
        "date_iso": r"^\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])$",
        "chinese_chars": r"[\u4e00-\u9fa5]+",
        "hex_color": r"^#(?:[0-9a-fA-F]{3}){1,2}$",
        "credit_card": r"^\d{13,19}$",
        "uuid": r"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$",
    }

    # 自然语言 -> 正则 映射表
    NL_PATTERNS = {
        "提取中国大陆手机号": r"1[3-9]\d{9}",
        "匹配邮箱地址": r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}",
        "匹配 IPv4 地址": r"(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)",
        "匹配中文字符": r"[\u4e00-\u9fa5]",
        "匹配 URL 链接": r"https?://[^\s]+",
        "匹配日期 YYYY-MM-DD": r"\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])",
        "提取数字": r"\d+",
        "匹配身份证号": r"[1-9]\d{5}(?:18|19|20)\d{2}(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\d|3[01])\d{3}[\dXx]",
    }

    def test(self, pattern: str, text: str, flags: int = 0) -> Dict[str, Any]:
        """测试正则表达式是否匹配目标文本"""
        try:
            compiled = re.compile(pattern, flags)
            match = compiled.match(text)
            if match:
                return {
                    "match": True,
                    "full_match": match.group(0) == text,
                    "groups": list(match.groups()) if match.groups() else [],
                    "groupdict": match.groupdict(),
                    "span": match.span(),
                }
            return {"match": False, "reason": "no match"}
        except re.error as e:
            return {"match": False, "reason": f"invalid pattern: {e}"}

    def explain(self, pattern: str) -> str:
        """将正则表达式翻译成人类可读的说明"""
        explanations = []

        # 分段解释常见模式
        mapping = {
            r"^": "字符串开头",
            r"$": "字符串结尾",
            r"\d+": "一个或多个数字",
            r"\d{3}": "恰好3位数字",
            r"\d{4}": "恰好4位数字",
            r"\d{8,}": "至少8位数字",
            r"\.": "一个点号",
            r"[A-Za-z0-9._%+-]+": "字母/数字/特殊字符组合",
            r"[a-zA-Z]+": "一个或多个英文字母",
            r"[\u4e00-\u9fa5]+": "一个或多个中文字符",
            r"(?=.*[A-Z])": "必须包含至少一个大写字母",
            r"(?=.*[a-z])": "必须包含至少一个小写字母",
            r"(?=.*\d)": "必须包含至少一个数字",
            r"(?=.*[!@#$%^&*])": "必须包含至少一个特殊符号",
            r".{8,}": "至少8个任意字符",
            r".{6,20}": "6到20个任意字符",
        }

        desc = pattern
        for pat, exp in mapping.items():
            if pat in pattern:
                explanations.append(exp)

        if not explanations:
            # 通用解释
            if pattern.startswith("^") and pattern.endswith("$"):
                return f"完整字符串匹配模式: 要求整个文本符合 '{pattern[1:-1]}' 的规则"
            return f"模式 '{pattern}' 的文本匹配规则"

        return "、".join(explanations)

    def generate(self, description: str) -> str:
        """根据自然语言描述生成正则表达式"""
        # 先匹配已知映射
        for key, pat in self.NL_PATTERNS.items():
            if key in description or description in key:
                return pat

        # 智能推断
        if "手机" in description or "电话" in description:
            return r"1[3-9]\d{9}"
        if "邮箱" in description or "email" in description.lower():
            return r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}"
        if "url" in description.lower() or "链接" in description:
            return r"https?://[^\s]+"
        if "身份证" in description:
            return r"[1-9]\d{5}(?:18|19|20)\d{2}(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\d|3[01])\d{3}[\dXx]"
        if "中文" in description:
            return r"[\u4e00-\u9fa5]+"
        if "数字" in description:
            return r"\d+"
        if "ipv4" in description.lower() or "ip 地址" in description:
            return r"(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)"

        return r".*"  # 默认通配

    def extract_all(self, pattern: str, text: str, flags: int = 0) -> List[str]:
        """从文本中提取所有匹配项"""
        try:
            compiled = re.compile(pattern, flags)
            return compiled.findall(text)
        except re.error:
            return []

    def get_template(self, name: str) -> Optional[str]:
        """获取内置正则模板"""
        return self.TEMPLATES.get(name)

    def list_templates(self) -> Dict[str, str]:
        """列出所有可用模板"""
        return dict(self.TEMPLATES)

    def validate_pattern(self, pattern: str) -> Dict[str, Any]:
        """验证正则表达式语法是否合法"""
        try:
            re.compile(pattern)
            return {"valid": True, "message": "pattern is valid"}
        except re.error as e:
            return {"valid": False, "message": str(e), "position": e.pos if hasattr(e, "pos") else None}

    def replace(self, pattern: str, text: str, replacement: str, flags: int = 0) -> str:
        """使用正则替换文本"""
        try:
            return re.sub(pattern, replacement, text, flags=flags)
        except re.error:
            return text


path: tests/test_regex_master.py
content: """
Regex Master 单元测试
"""
import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))

from scripts.regex_engine import RegexMaster


def test_test_method():
    rm = RegexMaster()
    assert rm.test(r"^\d{11}$", "13800138000")["match"] is True
    assert rm.test(r"^\d{11}$", "1380013800")["match"] is False
    assert rm.test(r"^(\d{3})-(\d{4})-(\d{4})$", "138-1234-5678")["groups"] == ["138", "1234", "5678"]
    print("✓ test_test_method passed")


def test_explain_method():
    rm = RegexMaster()
    exp = rm.explain(r"^(?=.*[A-Z])(?=.*\d).{8,}$")
    assert "大写字母" in exp or "数字" in exp or "至少8" in exp or "匹配模式" in exp
    print("✓ test_explain_method passed")


def test_generate_method():
    rm = RegexMaster()
    assert rm.generate("提取中国大陆手机号") == r"1[3-9]\d{9}"
    assert rm.generate("匹配邮箱地址") == r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}"
    assert "1[3-9]" in rm.generate("手机号")
    print("✓ test_generate_method passed")


def test_extract_all_method():
    rm = RegexMaster()
    text = "Contact: [REDACTED_SECRET], [REDACTED_SECRET], [REDACTED_SECRET]"
    matches = rm.extract_all(r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}", text)
    assert len(matches) == 3
    assert "[REDACTED_SECRET]" in matches
    print("✓ test_extract_all_method passed")


def test_templates():
    rm = RegexMaster()
    assert rm.get_template("email") is not None
    assert rm.get_template("phone_cn") is not None
    assert rm.get_template("nonexistent") is None
    assert "email" in rm.list_templates()
    print("✓ test_templates passed")


def test_validate_pattern():
    rm = RegexMaster()
    assert rm.validate_pattern(r"^[a-z]+$")["valid"] is True
    assert rm.validate_pattern(r"[a-z")["valid"] is False
    print("✓ test_validate_pattern passed")


def test_replace_method():
    rm = RegexMaster()
    text = "hello 123 world 456"
    result = rm.replace(r"\d+", text, "NUM")
    assert result == "hello NUM world NUM"
    print("✓ test_replace_method passed")


if __name__ == "__main__":
    test_test_method()
    test_explain_method()
    test_generate_method()
    test_extract_all_method()
    test_templates()
    test_validate_pattern()
    test_replace_method()
    print("\n所有测试通过! ✅")


Security scan verdicts — ClawScan: suspicious | static analysis: clean | VirusTotal: clean | SkillSpector: clean (LOW)