#regex #compile-time #right

ctreg

按本应如此的方式实现的编译时正则表达式

3个稳定版本

1.0.2 2024年5月10日
1.0.0 2024年5月8日

#6 in #right

Download history 108/week @ 2024-05-03 294/week @ 2024-05-10 178/week @ 2024-05-17 15/week @ 2024-05-24 43/week @ 2024-05-31 12/week @ 2024-06-07 28/week @ 2024-06-14 19/week @ 2024-06-21 3/week @ 2024-06-28 7/week @ 2024-07-05 4/week @ 2024-07-12 7/week @ 2024-07-19 33/week @ 2024-07-26 6/week @ 2024-08-02

51 每月下载量

MPL-2.0 许可证

18KB
226 代码行

ctreg

编译时正则表达式,正确的方式。


lib.rs:

ctreg(发音为 cuh-tredge,类似于Cthulhu)是一个宏,它使用编译时处理来使您的正则表达式更快、更易于使用。有关详细信息,请参阅regex宏。

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());

依赖项

~2.2–3.5MB
~69K SLoC