#random #regex #generator #string #random-string

rand_regex

Generates random strings and byte strings matching a regex

11 releases (7 breaking)

0.18.0 Jan 28, 2025
0.17.0 Jan 15, 2024
0.16.0 Aug 4, 2023
0.15.1 Feb 12, 2021
0.12.0 Nov 25, 2018

#52 in Algorithms

Download history 6925/week @ 2024-12-20 4946/week @ 2024-12-27 12451/week @ 2025-01-03 13108/week @ 2025-01-10 12788/week @ 2025-01-17 12760/week @ 2025-01-24 13276/week @ 2025-01-31 14388/week @ 2025-02-07 12242/week @ 2025-02-14 15039/week @ 2025-02-21 14595/week @ 2025-02-28 15565/week @ 2025-03-07 16442/week @ 2025-03-14 14377/week @ 2025-03-21 12120/week @ 2025-03-28 18457/week @ 2025-04-04

64,304 downloads per month
Used in 46 crates (15 directly)

MIT license

48KB
870 lines

rand_regex

Crates.io Build status MIT License

Generates random strings and byte strings matching a regex.

Examples

use rand::{SeedableRng, Rng};

let mut rng = rand_xorshift::XorShiftRng::from_seed(*b"The initial seed");

// creates a generator for sampling strings
let gen = rand_regex::Regex::compile(r"\d{4}-\d{2}-\d{2}", 100).unwrap();

// sample a few strings randomly
let samples = (&mut rng).sample_iter(&gen).take(3).collect::<Vec<String>>();

// all Unicode characters are included when sampling
assert_eq!(samples, vec![
    "꧰᪈৭᱃-𐒧᧒-௦۴".to_string(),
    "𞓰۳𑛐꩑-᪄9-໔᮹".to_string(),
    "𑛃𑃹९೭-١᥈-৫೪".to_string()
]);

// you could use `regex_syntax::Hir` to include more options
let mut parser = regex_syntax::ParserBuilder::new().unicode(false).build();
let hir = parser.parse(r"\d{4}-\d{2}-\d{2}").unwrap();
let gen = rand_regex::Regex::with_hir(hir, 100).unwrap();
let samples = (&mut rng).sample_iter(&gen).take(3).collect::<Vec<String>>();
assert_eq!(samples, vec![
    "2839-82-12".to_string(),
    "2857-86-63".to_string(),
    "0381-04-99".to_string(),
]);

Acknowledgement

rand_regex is heavily inspired by regex_generate and proptest.

Dependencies

~2.5MB
~51K SLoC