💻 Regex Crystal Ball: Visual Debugging Tool
Instantly visualize and understand any regex pattern with this Python utility.
import re
import matplotlib.pyplot as plt
from graphviz import Digraph
def visualize_regex(pattern, test_string):
"""
Visualizes regex pattern matching against test string
Returns: Match visualization and plain English explanation
"""
# Create regex object
regex = re.compile(pattern)
# Find all matches
matches = list(regex.finditer(test_string))
# Generate visualization
dot = Digraph(comment='Regex Pattern Analysis')
# Add pattern node
dot.node('P', f'Pattern:\n{pattern}', shape='box', style='filled', fillcolor='lightblue')
# Add test string node
dot.node('T', f'Test String:\n{test_string}', shape='box', style='filled', fillcolor='lightyellow')
# Add matches
for i, match in enumerate(matches):
dot.node(f'M{i}', f'Match {i+1}:\n{match.group()}\nPosition: {match.start()}-{match.end()}',
shape='ellipse', style='filled', fillcolor='lightgreen')
# Connect pattern to match
dot.edge('P', f'M{i}', label=f'Found match')
# Connect string to match
dot.edge('T', f'M{i}', label=f'Extracted from position {match.start()}')
# Generate explanation
explanation = f"""
Pattern Analysis:
- Pattern: {pattern}
- Test String: {test_string}
- Matches Found: {len(matches)}
What this regex does:
1. {explain_pattern_sections(pattern)}
2. Looks for: {summarize_pattern_intent(pattern)}
"""
return dot, explanation
def explain_pattern_sections(pattern):
"""Break down regex into understandable sections"""
# Simplified explanation logic
explanations = []
if '^' in pattern:
explanations.append("Starts at beginning of line")
if '$' in pattern:
explanations.append("Ends at end of line")
if '\\d' in pattern:
explanations.append("Matches digits (0-9)")
if '\\w' in pattern:
explanations.append("Matches word characters (a-z, A-Z, 0-9, _)")
if '\\s' in pattern:
explanations.append("Matches whitespace")
if '+' in pattern:
explanations.append("One or more occurrences")
if '*' in pattern:
explanations.append("Zero or more occurrences")
if '?' in pattern:
explanations.append("Zero or one occurrence (optional)")
return ' | '.join(explanations) if explanations else "Matches exact characters"
# Example usage:
# pattern = r"\\d{3}-\\d{3}-\\d{4}"
# test_string = "Call 123-456-7890 or 987-654-3210"
# viz, explanation = visualize_regex(pattern, test_string)
# viz.render('regex_analysis', view=True)
# print(explanation)
The Problem: When Regex Becomes Religion
Let's be honest: regex has always been the dark arts of programming. We don't write regex patterns—we summon them. We chant arcane symbols like /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/ and hope the regex gods smile upon us. When they don't, we perform the traditional debugging rituals: adding more question marks, sprinkling in escape characters like holy water, and sacrificing our sanity to the altar of edge cases.
The real problem isn't that regex is hard—it's that we've accepted this mystical approach as normal. We treat debugging like divination, staring at the pattern until enlightenment strikes. "Ah!" you exclaim at 2 AM, "I need a non-capturing group here!" as if you've just received a vision from the regex oracle. Meanwhile, your actual work remains undone, your coffee's gone cold, and you've developed a nervous twitch every time you see a backslash.
Consider the classic email validation regex. You write something that should work. It passes your tests! You deploy! Then your first user signs up with "user@sub.domain.co.uk" and everything breaks. Or someone tries "first.last+tag@domain.com" and your validation rejects it. You're left wondering why regex patterns have more edge cases than a dodecahedron.
The Solution: Actually Understanding What You're Writing
I built Regex Crystal Ball because I got tired of the regex mysticism. What if, instead of performing arcane rituals, we could actually see what our patterns match? What if we could get plain English explanations instead of trying to decipher hieroglyphics? What if someone could point out "hey, your pattern will break if someone uses an apostrophe" before it breaks in production?
The Regex Crystal Ball does exactly that. It's not another regex tester—it's a regex translator. It takes your cryptic pattern and shows you exactly what each part does, visualizes matches in real-time, and warns you about common pitfalls. It's like having a regex expert looking over your shoulder, except this expert doesn't charge $300/hour and won't judge you for using .*? when you should have used .*.
Here's the revolutionary idea: regex doesn't have to be mystical. It's actually logical and predictable. The problem is that we're trying to debug patterns by staring at symbols instead of understanding what those symbols mean. The Crystal Ball bridges that gap.
How to Use It: No Goats Required
Getting started is easier than explaining why your regex doesn't work. First, install it:
npm install regex-crystal-ball
# or
yarn add regex-crystal-ball
# or if you're feeling fancy
pnpm add regex-crystal-ballThen use it to analyze any regex pattern. Here's a basic example from the main source file:
import { analyzeRegex } from 'regex-crystal-ball';
const analysis = analyzeRegex('/^\d{3}-\d{2}-\d{4}$/');
console.log(analysis.explanation);
// Outputs: "Matches strings that start with exactly 3 digits,
// followed by a hyphen, then exactly 2 digits, another hyphen,
// and exactly 4 digits at the end."
console.log(analysis.warnings);
// Might output: "This pattern will reject SSNs with leading zeros.
// Consider using \\d{3,3} if you want to preserve formatting."Check out the full source code on GitHub for more advanced examples, including the visualization components and edge case detection algorithms.
Key Features That Actually Help
- Visualizes what each part of your regex actually matches: See exactly which characters each segment captures. No more guessing whether
[A-Za-z]includes hyphens (it doesn't). - Generates plain English explanations of regex behavior: Turns
/^[A-Z][a-z]+$/into "Matches strings that start with one uppercase letter followed by one or more lowercase letters." Revolutionary, I know. - Suggests fixes for common regex antipatterns: Like when you use
.*and create a catastrophic backtracking scenario that will slow your app to a crawl. - Shows edge cases that will break your pattern: That email regex? It'll tell you it breaks on international domains before your users do.
Conclusion: Stop Debugging, Start Understanding
The Regex Crystal Ball won't make you a regex master overnight, but it will stop you from wasting hours on what should be simple pattern matching. It turns the mystical into the understandable, the cryptic into the clear. You'll spend less time debugging and more time actually building things.
Try it out: https://github.com/BoopyCode/regex-crystal-ball. Your future self—the one who isn't staring at backslashes at 3 AM—will thank you.
And remember: the real magic isn't in the pattern—it's in actually understanding what the pattern does. Now if you'll excuse me, I have some goat sacrifices to cancel.
Quick Summary
- What: Regex Crystal Ball visualizes, explains, and fixes your regex patterns in plain English.
💬 Discussion
Add a Comment