4 releases (2 breaking)

0.3.0 Mar 21, 2025
0.2.0 Jan 29, 2022
0.1.1 Sep 9, 2020
0.1.0 Aug 31, 2020

#611 in Rust patterns

Download history 1128/week @ 2025-03-15 1016/week @ 2025-03-22 742/week @ 2025-03-29 1023/week @ 2025-04-05 815/week @ 2025-04-12 853/week @ 2025-04-19 1412/week @ 2025-04-26 845/week @ 2025-05-03 823/week @ 2025-05-10 1699/week @ 2025-05-17 1160/week @ 2025-05-24 1012/week @ 2025-05-31 876/week @ 2025-06-07 900/week @ 2025-06-14 1493/week @ 2025-06-21 853/week @ 2025-06-28

4,494 downloads per month
Used in 30 crates (26 directly)

MIT/Apache

8KB

regex-macro

Crates.io Version Docs.rs Latest Build Status

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?

License

This project is distributed under the terms of both the MIT license and the Apache License (Version 2.0).

See LICENSE-APACHE and LICENSE-MIT for details.

Dependencies

~2.6–4MB
~65K SLoC