2 releases

0.1.1 Mar 23, 2022
0.1.0 Mar 1, 2022

#1909 in Parser implementations

MIT license

85KB
2.5K SLoC

ESRE - Easy Regex

// 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");

Features

  • convinient variables
    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");
    }
    
  • convinient regex building in rust code checkout code in top block
  • json dump/load
    let dump: serde_json::Value = Re::create(...).to_json();
    let restored_re = Re::parse_json(&dump).unwrap().compile();
    

Available constructuions

  • match exactly Re::create("abc")
  • symbol in range Re::ranges(('a' ..= 'z')) - [a-z] Re::ranges((('a' ..= 'z'), '_')) - [a-z_] Re::ranges((('a' ..= 'z'), '_', ('0' ..= '9'))) - [a-z_0-9]
  • optional value Re::opt("abc")
  • wildcard value Re::any() - . Re::any().into_zero_or_more() - .*
  • repeats Re::zero_or_more("a") - a* Re::one_or_more("a") - a+ Re::repeat(min, max, "a") - repeat "a" max >= count >= min
  • begin/end Re::begin() Re::end()
  • anything except Re::not("x") Re::stop_all_if("x")
  • labels and vars Re::var("name", value) Re::label("name", value)
  • sequence of values join regexes into sequence using 'join' method Re::create("a").join(Re::any_of(("b", "c"))).join("d") use same named methods instead of Re::* Re::create("a").any_of(("b", "c")).opt("?") join values into one superclass using methods 'into_*' Re::ranges('a' ..= 'z').into_one_or_more().into_var("name")

Usage order

  1. build re with code using Re::* methods OR parse as json.
  2. call .compile() to make re ready to use.
  3. use re with methods .match_begin(...) .find(...) .find_all(...) .replace(...)

Dependencies

~0.6–1.4MB
~32K SLoC