2 个版本

0.1.1 2022年3月23日
0.1.0 2022年3月1日

#2049 in 解析器实现

MIT 许可证

85KB
2.5K SLoC

ESRE - 简易正则表达式

// Make regex for '[a-z]+'
let word = Re::ranges('a'..='z').into_one_or_more();
// Make regex for url format
let re = Re::create("http")
    .opt("s")
    .join("://")
    .join(word.clone())
    .one_or_more(Re::create(".").join(word))
    .opt("/")
    .compile();
// Check matches
let opt_val = re.match_begin("https://x.com.ru");

功能

  • 方便的变量
    let word = Re::ranges((('a' ..= 'z'), ('A' ..= 'Z'))).into_one_or_more().into_var("value");
    let name = Re::create("name").opt(":").zero_or_more(" ").join(word.clone()).into_label("name");
    let surname = Re::create("surname").opt(":").zero_or_more(" ").join(word.clone()).into_label("surname");
    let re = Re::create("hi").one_or_more(" ").any_of((
        name.clone().join(",").zero_or_more(" ").join(surname.clone()),
        surname.join(",").zero_or_more(" ").join(name),
    )).compile();
    
    for source in &["123 hi name:Gordon, surname: Freeman", "hi surname:Freeman,name:  Gordon"] {
        let found = re.find(source).unwrap();
        assert_eq!(found.get_var("name.value").unwrap(), "Gordon");
        assert_eq!(found.get_var("surname.value").unwrap(), "Freeman");
    }
    
  • 在 Rust 代码中方便地构建正则表达式,代码块顶部可查看代码
  • JSON 导出/导入
    let dump: serde_json::Value = Re::create(...).to_json();
    let restored_re = Re::parse_json(&dump).unwrap().compile();
    

可用构造

  • match exactly Re::create("abc")
  • 范围内的符号 Re::ranges(('a' ..= 'z')) - [a-z] Re::ranges((('a' ..= 'z'), '_')) - [a-z_] Re::ranges((('a' ..= 'z'), '_', ('0' ..= '9'))) - [a-z_0-9]
  • 可选值 Re::opt("abc")
  • 通配符值 Re::any() - . Re::any().into_zero_or_more() - .*
  • 重复 Re::zero_or_more("a") - a* Re::one_or_more("a") - a+ Re::repeat(min, max, "a") - repeat "a" max >= count >= min
  • 开始/结束 Re::begin() Re::end()
  • 除了 Re::not("x")Re::stop_all_if("x")
  • 标签和变量 Re::var("name", value) Re::label("name", value)
  • 值的序列将正则表达式连接成序列,使用 'join' 方法 Re::create("a").join(Re::any_of(("b", "c"))).join("d") 使用同名方法而不是 Re::* Re::create("a").any_of(("b", "c")).opt("?") 使用方法 'into_*' 将值连接到一个超类 Re::ranges('a' ..= 'z').into_one_or_more().into_var("name")

使用顺序

  1. 使用 Re::* 方法使用代码构建 re 或解析为 json。
  2. 调用 .compile() 使 re 准备好使用。
  3. 使用方法 .match_begin(...) .find(...) .find_all(...) .replace(...) 使用 re。

依赖项

~0.7–1.6MB
~35K SLoC