mcpField
R
regex-tester

regex-tester

github.com/dkyazzentwatwa开发12457 次安装29 周前更新
代码仓库

关于 regex-tester

regex-tester 用于测试、调试和理解正则表达式,面向编写模式或检查文本匹配的开发者。它还可从示例生成模式,并测试替换和语法有效性。

主要功能

  1. 01测试模式并查看匹配结果
  2. 02可视化匹配内容与位置
  3. 03用自然语言解释模式
  4. 04根据示例生成模式
  5. 05测试查找与替换
  6. 06验证语法并提供常用模式

适用场景

  1. 01调试文本处理用的正则表达式
  2. 02检查文本或文件中的匹配项
  3. 03从样例生成匹配模式
  4. 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