Generate Regular Expressions with Grex CLI

Developer Tools

April 13th, 2021

grex-featured.png

Grex is a command-line tool and library for generating regular expressions from user-provided test cases. Grex is both a library (Rust) and a command-line tool meant to simplify creating regular expressions.

Here's a simple example from the project's readme to help you visualize how it works as a CLI tool for building regexes:

1grex -c \
2 "regexes are awesome" \
3 "regexes are awful"
4^regexes are aw(?:esome|ful)$

While Grex is awesome at creating a valid regex based on input, you can, of course, refine and optimize the regular expression further. Let's say you provide a list of URLs that you want to match via Grex. You might intend to support both HTTP and HTTPS for all domains, but the example provided doesn't include the HTTP version of all domains you want to match:

1grex -c \
2 "https://example.com" \
3 "https://example.org" \
4 "http://example.net" \
5 "https://example.net"
6 
7^http(?:s://example\.(?:com|net|org)|://example\.net)$

Here's an example of visualizing how the above samples would match against additional output:

Testing Grex regex against input

Perhaps you could further optimize this pattern using something like the following regex:

1https?://example\.(com|org|net)

Understand that while the first example is technically accurate based on the input provided, you might not be providing enough sample data to build the expected regex. This example is just to illustrate how to use Grex works based on the provided input.

Grex is also a library for Rust, check out the readme for details. You can learn more about this CLI tool, get full installation instructions, and view the source code on GitHub.

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.