A command-line tool and Rust library with Python bindings for generating regular expressions from user-provided test cases
A command-line tool and Rust library with Python bindings for generating regular expressions from user-provided test cases
grex is a library as well as a command-line utility that is meant to simplify the often complicated and tedious task of creating regular expressions. It does so by automatically generating a single regular expression from user-provided test cases. The resulting expression is guaranteed to match the test cases which it was generated from.
This project has started as a Rust port of the JavaScript tool regexgen written by Devon Govett. Although a lot of further useful features could be added to it, its development was apparently ceased several years ago. The plan is now to add these new features to grex as Rust really shines when it comes to command-line tools. grex offers all features that regexgen provides, and more.
The philosophy of this project is to generate the most specific regular expression possible by default which exactly matches the given input only and nothing else. With the use of command-line flags (in the CLI tool) or preprocessing methods (in the library), more generalized expressions can be created.
The produced expressions are Perl-compatible regular expressions which are also compatible with the regular expression parser in Rust's regex crate. Other regular expression parsers or respective libraries from other programming languages have not been tested so far, but they ought to be mostly compatible as well.
Definitely, yes! Using the standard settings, grex produces a regular expression that is guaranteed
to match only the test cases given as input and nothing else.
This has been verified by property tests.
However, if the conversion to shorthand character classes such as \w is enabled, the resulting regex matches
a much wider scope of test cases. Knowledge about the consequences of this conversion is essential for finding
a correct regular expression for your business domain.
grex uses an algorithm that tries to find the shortest possible regex for the given test cases. Very often though, the resulting expression is still longer or more complex than it needs to be. In such cases, a more compact or elegant regex can be created only by hand. Also, every regular expression engine has different built-in optimizations. grex does not know anything about those and therefore cannot optimize its regexes for a specific engine.
So, please learn how to write regular expressions! The currently best use case for grex is to find an initial correct regex which should be inspected by hand if further optimizations are possible.
{min,max} quantifier notation| operator? quantifier^ and $You can download the self-contained executable for your platform above and put it in a place of your choice. Alternatively, pre-compiled 64-Bit binaries are available within the package managers Scoop (for Windows), Homebrew (for macOS and Linux), MacPorts (for macOS), and Huber (for macOS, Linux and Windows). Raúl Piracés has contributed a Chocolatey Windows package.
grex is also hosted on crates.io, the official Rust package registry. If you are a Rust developer and already have the Rust toolchain installed, you can install by compiling from source using cargo, the Rust package manager. So the summary of your installation options is:
( brew | cargo | choco | huber | port | scoop ) install grexIn order to use grex as a library, simply add it as a dependency to your Cargo.toml file:
[dependencies]
grex = { version = "1.4.6", default-features = false }The dependency clap is only needed for the command-line tool. By disabling the default features, the download and compilation of clap is prevented for the library.
Detailed explanations of the available settings are provided in the library section. All settings can be freely combined with each other.
Test cases are passed either directly (grex a b c) or from a file (grex -f test_cases.txt).
grex is able to receive its input from Unix pipelines as well, e.g. cat test_cases.txt | grex -.
The following table shows all available flags and options:
…Test cases are passed either from a collection via RegExpBuilder::from()
or from a file via RegExpBuilder::from_file().
If read from a file, each test case must be on a separate line. Lines may be ended with either a newline \n or a carriage
return with a line feed \r\n.
use grex::RegExpBuilder;
let regexp = RegExpBuilder::from(&["a", "aa", "aaa"]).build();
assert_eq!(regexp, "^a(?:aa?)?$");use grex::RegExpBuilder;
let regexp = RegExpBuilder::from(&["a", "aa", "123"])
.with_conversion_of_digits()
.with_conversion_of_words()
.build();
assert_eq!(regexp, "^(\\d\\d\\d|\\w(?:\\w)?)$");use grex::RegExpBuilder;
let regexp = RegExpBuilder::from(&["aa", "bcbc", "defdefdef"])
.with_conversion_of_repetitions()
.build();
assert_eq!(regexp, "^(?:a{2}|(?:bc){2}|(?:def){3})$");By default, grex converts each substring this way which is at least a single character long and which is subsequently repeated at least once. You can customize these two parameters if you like.
In the following example, the test case aa is not converted to a{2} because the repeated substring
a has a length of 1, but the minimum substring length has been set to 2.
use grex::RegExpBuilder;
let regexp = RegExpBuilder::from(&["aa", "bcbc", "defdefdef"])
.with_conversion_of_repetitions()
.with_minimum_substring_length(2)
.build();
assert_eq!(regexp, "^(?:aa|(?:bc){2}|(?:def){3})$");Setting a minimum number of 2 repetitions in the next example, only the test case defdefdef will be
converted because it is the only one that is repeated twice.
use grex::RegExpBuilder;
let regexp = RegExpBuilder::from(&["aa", "bcbc", "defdefdef"])
.with_conversion_of_repetitions()
.with_minimum_repetitions(2)
.build();
assert_eq!(regexp, "^(?:bcbc|aa|(?:def){3})$");use grex::RegExpBuilder;
let regexp = RegExpBuilder::from(&["You smell like ."])
.with_escaping_of_non_ascii_chars(false)
.build();
assert_eq!(regexp, "^You smell like \\\u{1f4a9}\\.$");Old versions of JavaScript do not support unicode escape sequences for the astral code planes
(range U+010000 to U+10FFFF). In order to support these symbols in JavaScript regular
expressions, the conversion to surrogate pairs is necessary. More information on that matter
can be found here.
use grex::RegExpBuilder;
let regexp = RegExpBuilder::from(&["You smell like ."])
.with_escaped_non_ascii_chars(true)
.build();
assert_eq!(regexp, "^You smell like \\\u{d83d}\\\u{dca9}\\.$");The regular expressions that grex generates are case-sensitive by default. Case-insensitive matching can be enabled like so:
use grex::RegExpBuilder;
let regexp = RegExpBuilder::from(&["big", "BIGGER"])
.with_case_insensitive_matching()
.build();
assert_eq!(regexp, "(?i)^big(?:ger)?$");Non-capturing groups are used by default. Extending the previous example, you can switch to capturing groups instead.
use grex::RegExpBuilder;
let regexp = RegExpBuilder::from(&["big", "BIGGER"])
.with_case_insensitive_matching()
.with_capturing_groups()
.build();
assert_eq!(regexp, "(?i)^big(ger)?$");If you find the generated regular expression hard to read, you can enable verbose mode. The expression is then put on multiple lines and indented to make it more pleasant to the eyes.
use grex::RegExpBuilder;
use indoc::indoc;
let regexp = RegExpBuilder::from(&["a", "b", "bcd"])
.with_verbose_mode()
.build();
assert_eq!(regexp, indoc!(
r#"
(?x)
^
(?:
b
(?:
cd
)?
|
a
)
$"#
));By default, the anchors ^ and $ are put around every generated regular expression in order
to ensure that it matches only the test cases given as input. Often enough, however, it is
desired to use the generated pattern as part of a larger one. For this purpose, the anchors
can be disabled, either separately or both of them.
use grex::RegExpBuilder;
let regexp = RegExpBuilder::from(&["a", "aa", "aaa"])
.without_anchors()
.build();
assert_eq!(regexp, "a(?:aa?)?");The following examples show the various supported regex syntax features:
$ grex a b c
^[a-c]$
$ grex a c d e f
^[ac-f]$
$ grex a b x de
^(?:de|[abx])$
$ grex abc bc
^a?bc$
$ grex a b bc
^(?:bc?|a)$
$ grex [a-z]
^\[a\-z\]$
$ grex -r b ba baa baaa
^b(?:a{1,3})?$
$ grex -r b ba baa baaaa
^b(?:a{1,2}|a{4})?$
$ grex y̆ a z
^(?:y̆|[az])$
Note:
Grapheme y̆ consists of two Unicode symbols:
U+0079 (Latin Small Letter Y)
U+0306 (Combining Breve)
$ grex "I ♥ cake" "I ♥ cookies"
^I ♥ c(?:ookies|ake)$
Note:
Input containing blank space must be
surrounded by quotation marks.The string "I ♥♥♥ 36 and ٣ and ." serves as input for the following examples using the command-line notation:
…In order to build the source code yourself, you need the stable Rust toolchain installed on your machine so that cargo, the Rust package manager is available. Please note: Rust >= 1.70.0 is required to build the CLI. For the library part, Rust < 1.70.0 is sufficient.
git clone https://github.com/pemistahl/grex.git
cd grex
cargo buildThe source code is accompanied by an extensive test suite consisting of unit tests, integration tests and property tests. For running them, simply say:
cargo testBenchmarks measuring the performance of several settings can be run with:
cargo benchWith the help of [PyO3](https
CLI panics on empty input and on invalid UTF-8 input from stdin
Problem on console without support of color.
Non optimal generated regexp
Provide more installation options
Performance enhancements to enable large inputs
Allow to specify characters that have to be converted to character class
Treat diffs as separate groups
Generate BRE and ERE regex
Allow to provide test cases that must not be matched