1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
use regex::Regex;
use thiserror::Error;
#[derive(Error, Debug)]
pub enum Error {
#[error("An regex error occurred")]
RegexError(#[from] regex::Error),
}
pub type Result<T> = std::result::Result<T, Error>;
pub trait AsRegex: ToString {
fn as_regex(&self) -> Result<Regex> {
let regex = Regex::new(&self.to_string())?;
Ok(regex)
}
}
pub trait Condition: AsRegex + Sized {
fn and(self, other: impl AsRegex) -> Regex {
Regex::new(&format!("{}{}", self.to_string(), other.to_string()))
.expect("Invalid regex (and)")
}
fn or(self, other: impl AsRegex) -> Regex {
Regex::new(&format!("{}|{}", self.to_string(), other.to_string()))
.expect("Invalid regex (or)")
}
fn optionally(self) -> Regex {
Regex::new(&format!("({})?", self.to_string())).expect("Invalid regex (optionally)")
}
}