Crate regex_macro

Source
Expand description

This crate contains a little macro to generate a lazy Regex and remove some boilerplate when compiling regex expressions.

§Usage

Since it is an anti-pattern to compile the same regular expression in a loop this means for most regex expressions you need to store them in a LazyLock in a static. But this can get a bit tiresome with many regex expressions. This crate provides a regex! macro that will store the compiled regex in a global static and return a reference to it.

§Before

use std::sync::LazyLock;
use regex::Regex;

// only compiled once, by storing in a static
static HEX_PATTERN: LazyLock<Regex> = LazyLock::new(|| {
   Regex::new("[0-9a-f]+").expect("invalid regex")
});

for item in my_iter {
    if HEX_PATTERN.is_match(item) {
       // frobnicate
    }
}

§After

use regex_macro::regex;

for item in my_iter {
    // this is still only compiled once!
    if regex!("[0-9a-f]+").is_match(item) {
       // frobnicate
    }
}

Isn’t that much nicer?

Macros§

lazy_regex
Returns a lazy regex.
regex
Creates a static regex and returns a reference to it.

Type Aliases§

LazyRegex
Convenient type alias for a lazy regex.