πŸ“ Tutorials
Β· 5 min read

Build a Local AI Regex Generator β€” Describe It, Get Regex


Regex is powerful but hard to write. You know what you want to match, but translating that into the right pattern takes forever. What if you could describe it in English and get working regex?

In this tutorial, you’ll build a regex generator that takes natural language descriptions and produces regular expressions. No API keys, no cloud calls, everything runs on your machine.

How It Works

  1. You describe what to match: β€œemail addresses”
  2. AI generates the regex pattern
  3. You get the pattern, an explanation, and test cases

Prerequisites

  • Ollama installed
  • Python 3.10+

Step 1: Pull the model

ollama pull qwen2.5-coder:7b

Step 2: Create the regex generator

#!/usr/bin/env python3
"""AI regex generator using Ollama."""

import subprocess
import sys
import json
import urllib.request
import re

OLLAMA_URL = "http://localhost:11434/api/generate"
MODEL = "qwen2.5-coder:7b"

PROMPT_TEMPLATE = """Generate a regular expression for the following pattern.

Description: {description}
Language: {language}

Requirements:
1. Create a regex that matches the described pattern
2. Make it as specific as possible
3. Handle edge cases where reasonable
4. Use named groups if helpful

Output format:
- REGEX: the pattern
- EXPLANATION: brief explanation of how it works
- TESTS: 3-5 test cases (matches and non-matches)

Example:
Input: email addresses
Output:
REGEX: ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$
EXPLANATION: Matches standard email format with local@domain.tld
TESTS: user@example.com (match), invalid@ (no match), @no-local.com (no match)

Now generate for: {description}"""


def generate_regex(description, language="python"):
    """Generate regex from natural language."""
    payload = json.dumps({
        "model": MODEL,
        "prompt": PROMPT_TEMPLATE.format(
            description=description,
            language=language
        ),
        "stream": False,
        "options": {"temperature": 0.3, "num_predict": 500}
    }).encode()

    req = urllib.request.Request(
        OLLAMA_URL,
        data=payload,
        headers={"Content-Type": "application/json"}
    )

    with urllib.request.urlopen(req, timeout=60) as resp:
        response = json.loads(resp.read())["response"].strip()
        return parse_response(response)


def parse_response(response):
    """Parse the AI response into structured data."""
    result = {"regex": "", "explanation": "", "tests": []}

    lines = response.split("\n")
    current_section = None

    for line in lines:
        line = line.strip()
        if line.startswith("REGEX:"):
            result["regex"] = line[6:].strip()
            current_section = None
        elif line.startswith("EXPLANATION:"):
            result["explanation"] = line[12:].strip()
            current_section = None
        elif line.startswith("TESTS:"):
            current_section = "tests"
        elif current_section == "tests" and line:
            result["tests"].append(line)

    return result


def test_regex(pattern, test_cases):
    """Test the generated regex against test cases."""
    try:
        compiled = re.compile(pattern)
    except re.error as e:
        print(f"Invalid regex: {e}")
        return False

    print(f"\nTesting regex: {pattern}")
    print("-" * 50)
    for test in test_cases:
        if "(match)" in test:
            test_str = test.replace(" (match)", "").strip()
            match = compiled.search(test_str)
            status = "PASS" if match else "FAIL"
            print(f"  {status}: '{test_str}' should match")
        elif "(no match)" in test:
            test_str = test.replace(" (no match)", "").strip()
            match = compiled.search(test_str)
            status = "PASS" if not match else "FAIL"
            print(f"  {status}: '{test_str}' should NOT match")
        else:
            print(f"  TEST: {test}")

    return True


def interactive_mode():
    """Interactive regex generation."""
    print("AI Regex Generator")
    print("Type 'quit' to exit")
    print()

    while True:
        description = input("Describe what to match: ").strip()
        if description.lower() in ["quit", "exit", "q"]:
            break

        language = input("Language (python/javascript/java) [python]: ").strip() or "python"

        print("\nGenerating regex...")
        result = generate_regex(description, language)

        print(f"\n{'=' * 50}")
        print(f"Pattern: {result['regex']}")
        print(f"Explanation: {result['explanation']}")
        print(f"{'=' * 50}")

        if result["tests"]:
            test_regex(result["regex"], result["tests"])

        print()


if __name__ == "__main__":
    if len(sys.argv) > 1:
        # One-shot mode
        description = " ".join(sys.argv[1:])
        result = generate_regex(description)
        print(f"Pattern: {result['regex']}")
        print(f"Explanation: {result['explanation']}")
        if result["tests"]:
            test_regex(result["regex"], result["tests"])
    else:
        interactive_mode()

Step 3: Use it

# One-shot mode
python regex_generator.py "phone numbers in US format"

# Interactive mode
python regex_generator.py

Example Session

Describe what to match: dates in YYYY-MM-DD format

Generating regex...

==================================================
Pattern: ^\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])$
Explanation: Matches dates in YYYY-MM-DD format with valid month (01-12) and day (01-31)
==================================================

Testing regex: ^\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])$
--------------------------------------------------
  PASS: '2026-07-21' should match
  PASS: '2026-13-01' should NOT match
  PASS: '2026-02-30' should NOT match
  PASS: 'not-a-date' should NOT match

What Makes This Different

The AI understands context and edge cases:

  • Email regex: Handles edge cases like subdomains and special characters
  • Phone numbers: Handles international formats and optional components
  • Dates: Validates month/day ranges, not just number patterns
  • URLs: Handles protocols, ports, query parameters

The AI also provides clear explanations, making the regex maintainable.

Common Use Cases

DescriptionUse Case
Email addressesForm validation
Phone numbersContact forms
URLsLink extraction
DatesData parsing
IP addressesNetwork tools
Credit card numbersPayment validation
Hex colorsCSS tools

Limitations

  • Very complex patterns may need manual refinement
  • Performance-critical regex should be optimized manually
  • Some edge cases may be missed
  • Generated regex may be more complex than necessary

Real-World Use Cases

Form validation. Generate regex for email, phone, URL, and date fields. The AI handles edge cases you might miss.

Log parsing. Extract specific information from log files. Describe what you want to extract and get the pattern.

Data cleaning. Clean messy data by identifying patterns that need transformation.

API request validation. Validate API parameters against expected formats.

Security scanning. Detect sensitive data patterns (credit cards, SSNs, emails) in code or logs.

Tips for Better Patterns

  1. Be specific. β€œUS phone numbers” is better than β€œphone numbers.”
  2. Include examples. β€œDates like 2026-07-21” helps the AI understand the format.
  3. Mention exclusions. β€œEmails but not internal @company.com addresses” gives more precise patterns.
  4. Test thoroughly. Always test with real data before deploying.

My Take

This tool makes regex accessible to everyone. Instead of spending 20 minutes crafting a pattern, you get one in seconds. The explanation feature also teaches you regex while you use it.

Rating: 8/10 β€” Essential for anyone who works with text processing.

FAQ

How accurate is the generated regex?

Very accurate for common patterns (emails, phones, dates). For specialized patterns, the regex may need tweaking. Always test with your actual data.

Can I generate regex for other languages?

Yes. Specify the language (Python, JavaScript, Java, etc.) and the AI will use appropriate syntax and features.

Can I use this to learn regex?

Yes. The explanation feature teaches you how each pattern works. Generate a pattern, read the explanation, and you understand regex better.

What if the generated regex doesn’t work?

Try rephrasing the description. Be more specific about what you want to match and what you want to exclude.

Related: Regex Cheat Sheet Β· Python String Processing Β· Ollama Complete Guide