How to Beginner to Intermediate · 3 min read

How to use AI for regular expressions

Quick answer
Use AI models like gpt-4o to generate, explain, or debug regular expressions by prompting them with your pattern requirements or sample text. You can call the chat.completions.create API with clear instructions to get regex patterns or explanations instantly.

PREREQUISITES

  • Python 3.8+
  • OpenAI API key (free tier works)
  • pip install openai>=1.0

Setup

Install the OpenAI Python SDK and set your API key as an environment variable for secure access.

bash
pip install openai>=1.0

Step by step

This example shows how to prompt gpt-4o to generate a regex that matches email addresses, then prints the result.

python
import os
from openai import OpenAI

client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])

prompt = (
    "Generate a Python regular expression pattern that matches valid email addresses. "
    "Explain the pattern briefly."
)

response = client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": prompt}]
)

print(response.choices[0].message.content)
output
r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}"  # Matches typical email addresses

Common variations

You can also use AI to explain existing regex patterns, debug them by providing failing examples, or generate regex for different languages like JavaScript. Using async calls or streaming responses is possible with the OpenAI SDK.

python
import asyncio
import os
from openai import OpenAI

async def async_regex_generation():
    client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
    prompt = "Create a regex to match US phone numbers in format (123) 456-7890."
    response = await client.chat.completions.acreate(
        model="gpt-4o",
        messages=[{"role": "user", "content": prompt}]
    )
    print(response.choices[0].message.content)

asyncio.run(async_regex_generation())
output
\\(\\d{3}\\) \\d{3}-\\d{4}  # Matches US phone numbers like (123) 456-7890

Troubleshooting

  • If the AI generates incorrect or overly broad regex, refine your prompt with examples of matching and non-matching strings.
  • If you get API errors, verify your OPENAI_API_KEY environment variable is set correctly.
  • For complex regex, ask the AI to explain each part to ensure correctness.

Key Takeaways

  • Use clear, specific prompts to get accurate regex from AI models like gpt-4o.
  • AI can generate, explain, and debug regex patterns, saving development time.
  • Always validate AI-generated regex with test cases to ensure correctness.
Verified 2026-04 · gpt-4o
Verify ↗