#regex #compile-time #regular #expressions #meant

ctreg

Compile-time regular expressions the way they were always meant to be

3 stable releases

1.0.2 May 10, 2024
1.0.0 May 8, 2024

#4 in #meant

Download history 25/week @ 2024-07-20 16/week @ 2024-07-27 4/week @ 2024-08-03 4/week @ 2024-08-17 6/week @ 2024-09-14 10/week @ 2024-09-21 4/week @ 2024-09-28 8/week @ 2024-10-05 34/week @ 2024-10-12 3/week @ 2024-10-19 5/week @ 2024-10-26 9/week @ 2024-11-02

52 downloads per month

MPL-2.0 license

18KB
226 lines

ctreg

Compile-time regular expressions, the right way.


lib.rs:

ctreg (pronounced cuh-tredge, in the style of Cthulhu) is a macro that uses compile-time processing to make your regular expressions faster and easier to use. See the regex macro for details.

use ctreg::regex;

// Create a regular expression with the macro. This regular expression is
// evaluated at compile time and its parsed, normalized representation is
// emitted as the `HelloWorld` type.
regex! { pub HelloWorld = "(?<greeting>[a-zA-Z0-9-_.]+)(, (?<target>[a-zA-Z0-9-_.]+))?!" }

// Create an instance of the regular expression.
let regex = HelloWorld::new();

// Use `is_match` to test if there was a match
assert!(regex.is_match("Hello, World!"));
assert!(regex.is_match("Goodbye!"));
assert!(!regex.is_match("Nothing to see here."));

// Use `find` to find the location of a match
let cap = regex.find("abc Greetings, Rustacean! 123").unwrap();
assert_eq!(cap.content, "Greetings, Rustacean!");
assert_eq!(cap.start, 4);
assert_eq!(cap.end, 25);

assert!(regex.find("Nothing to see here.").is_none());

// Use `captures` to find all of the named capture groups of a match (`greeting`
// and `target`, in this case). Capture groups are emitted at compile time and
// evaluated infallibly.
let groups = regex.captures("ah, Bonjour, reader!").unwrap();
assert_eq!(groups.greeting.content, "Bonjour");
assert_eq!(groups.target.unwrap().content, "reader");

let groups = regex.captures("This is goodbye!").unwrap();
assert_eq!(groups.greeting.content, "goodbye");
assert!(groups.target.is_none());

assert!(regex.captures("nothing to see here.").is_none());

Dependencies

~2.2–3.5MB
~70K SLoC