Blog

How to get out of Regex hell with GPT-3 (OpenAI)

Team Avatar - Kane Hooper
Kane Hooper
May 16, 2023

For the past 5-years I have managed approximately 100 senior Ruby and Rails software developers and almost 1-for-1 they hate dealing with Regex.

They especially get frustrated when I say, “Why don’t you just validate it with Regex? It’s simple right?”

Well, Regex pain is a thing of the past. By using GPT-3 you can ask the AI to generate the Regex pattern through the use of natural language. Just tell the AI model what you want and it will provide a Regex pattern to include in your code. You can even go so far as have the AI generate the function for you.

And just to show how crazy simple it is, I had the AI output the code in JavaScript, Ruby, Python, Rust, Go and C++ (I am not familiar with those last three).


REGEX HELL

An impressionist painting of a Regex pattern created by Dalle-2


The key to generating the Regex is the prompt. This is the instruction to the AI. It sometimes requires some fiddling and playing around to get the exact response you are looking for from the AI.

I did find the Regex pattern being provided by the AI was changing between languages. This is likely due to the temperature setting which I had at 0.7 which is quite high and introduces a high degree of randomness.


Prompt

Here is the prompt I used to instruct the AI:



You are a Ruby developer. Write a function that takes a string and validates if it is an email address using Regex.


You will notice in the examples below I am using the OpenAI playground as opposed to ChatGPT. I find the playground a lot more efficient to work with and it gives you greater control over the parameters. You will need to sign up for an OpenAI account to get access to the playground.


Javascript

Javascript


Ruby

Ruby


Python

Python


Rust

RUST


GO

GO


C++

C++

Summary

The good news about GPT providing Regex patterns so quickly, is I would feel more confident using Regex where I might have tried other approaches to manipulate code. But one big warning, TEST, TEST, TEST. GPT is not infallible, it makes mistakes. It is not a full substitute for an intelligent and skilled developer.


Integrating Ruby with OpenAI: A Beginner’s Guide

Creating an AI Email Parser Using Ruby and OpenAI (GPT-3)

How to Generate OpenAI (GPT-3) Output in JSON Format for Ruby developers

Transforming Education: Using OpenAI and Ruby to Summarise Wikipedia for Children