#regex #magic #expression

magic-regexp

一个轻松创建正则表达式的库

6 个版本

0.2.0 2024年5月29日
0.1.4 2023年3月4日
0.1.3 2023年2月26日

7#magic

每月 40 次下载

MIT 许可

20KB
238

magic-regexp

此库旨在简化您的正则表达式体验,无需每次使用时都学习正则表达式。因此,它实现了一种易于阅读的语法。此外,它可以用于与优秀的 regex crate 一起工作。因此,您无需再实现随机的正则表达式字符串,而是编写原生且易于阅读的 rust 代码。

文档

文档可以在 此处 找到。

用法

要将此 crate 添加到您的存储库中,请在 Cargo.toml 中添加 magic-regexp,或运行 cargo add magic-regexp

以下是一个简单的示例,它匹配 YYYY-MM-DD 格式的日期并打印年、月和日

use magic_regexp::{Digit, Times, create_reg_exp, Exactly, Condition, Text};
use regex::Regex;

fn main() {
    let input = Times(Digit, 4)
        .and(Exactly(Text("-")))
        .and(Times(Digit, 2))
        .and(Exactly(Text(("-"))))
        .and(Times(Digit, 2));
    assert_eq!(input.to_string(), r"\d{4}-\d{2}-\d{2}");

    let input = Times(Digit, 4)
        .grouped_as("year")
        .and(Exactly(Text("-")))
        .and(Times(Digit, 2)
            .grouped_as("month"))
        .and(Exactly(Text(("-"))))
        .and(Times(Digit, 2)
            .grouped_as("day"));
    let re = create_reg_exp(input).unwrap();
    assert!(re.is_match("2014-01-01"));
    
    const TO_SEARCH: &'static str = "On 2010-03-14, foo happened. On 2014-10-14, bar happened.";
    assert_eq!(re.find_iter(TO_SEARCH).count(), 2);

    // works with lib regex like before
    for caps in re.captures_iter(TO_SEARCH) {
        // Note that all of the unwraps are actually OK for this regex
        // because the only way for the regex to match is if all of the
        // capture groups match. This is not true in general though!
        println!("year: {}, month: {}, day: {}",
                 caps.get(1).unwrap().as_str(),
                 caps.get(2).unwrap().as_str(),
                 caps.get(3).unwrap().as_str());
    }
}

寻求帮助

这是我第一个 Rust 库,我不确定我是否做得完全正确。因此,如果您有任何建议或发现错误,请通过 github issues 告诉我。

灵感

此库在很大程度上受到了 magic-regexp 的启发。

依赖项

~2.4–4MB
~70K SLoC