Skip to content

Commit fef5e76

Browse files
committed
feat(str): Regex predicate
This is a short term API. Different issues we'll need to consider when evolving this include: - Easy to create predicate - The ability to customize the regex (e.g. case sensitivity, multi-line, ignoring whityespace). - It looks like the flags can be enabled with `(?flag)` inside the regex. Good enough? - How error handling should work. Re-export? A single error type for the whole crate? This is a part of assert-rs#12
1 parent 9a102cb commit fef5e76

File tree

4 files changed

+49
-1
lines changed

4 files changed

+49
-1
lines changed

Cargo.toml

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,8 @@ appveyor = { repository = "assert-rs/predicates-rs" }
1919

2020
[dependencies]
2121
difference = { version = "2.0", optional = true }
22+
regex = { version="0.2", optional = true }
2223

2324
[features]
24-
default = ["difference"]
25+
default = ["difference", "regex"]
2526
unstable = []

src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,8 @@
8787

8888
#[cfg(feature = "difference")]
8989
extern crate difference;
90+
#[cfg(feature = "regex")]
91+
extern crate regex;
9092

9193
// core `Predicate` trait
9294
pub mod predicate;

src/predicate/str/mod.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,3 +6,8 @@
66
mod difference;
77
#[cfg(feature = "difference")]
88
pub use self::difference::{diff, DifferencePredicate};
9+
10+
#[cfg(feature = "regex")]
11+
mod regex;
12+
#[cfg(feature = "regex")]
13+
pub use self::regex::{is_match, RegexError, RegexPredicate};

src/predicate/str/regex.rs

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
use regex;
2+
3+
use Predicate;
4+
5+
/// An error that occurred during parsing or compiling a regular expression.
6+
pub type RegexError = regex::Error;
7+
8+
/// Predicate that uses regex matching
9+
///
10+
/// This is created by the `predicate::str::is_match`.
11+
#[derive(Clone, Debug)]
12+
pub struct RegexPredicate {
13+
re: regex::Regex,
14+
}
15+
16+
impl Predicate for RegexPredicate {
17+
type Item = str;
18+
19+
fn eval(&self, variable: &str) -> bool {
20+
self.re.is_match(variable)
21+
}
22+
}
23+
24+
/// Creates a new `Predicate` that diffs two strings.
25+
///
26+
/// # Examples
27+
///
28+
/// ```
29+
/// use predicates::predicate::*;
30+
///
31+
/// let predicate_fn = str::is_match("^Hel.o.*$").unwrap();
32+
/// assert_eq!(true, predicate_fn.eval("Hello World"));
33+
/// assert_eq!(false, predicate_fn.eval("Food World"));
34+
/// ```
35+
pub fn is_match<S>(pattern: S) -> Result<RegexPredicate, RegexError>
36+
where
37+
S: AsRef<str>,
38+
{
39+
regex::Regex::new(pattern.as_ref()).map(|re| RegexPredicate { re })
40+
}

0 commit comments

Comments
 (0)