hamcrest2/matchers/
regex.rs

1// Copyright 2016 Urban Hafner
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6// option. This file may not be copied, modified, or distributed
7// except according to those terms.
8
9use regex::Regex;
10use std::borrow::Borrow;
11use std::fmt;
12
13use crate::core::*;
14
15pub struct MatchesRegex {
16  regex: Regex,
17}
18
19impl fmt::Display for MatchesRegex {
20  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
21    self.regex.fmt(f)
22  }
23}
24
25impl<B: Borrow<str>> Matcher<B> for MatchesRegex {
26  fn matches(&self, actual: B) -> MatchResult {
27    if self.regex.is_match(actual.borrow()) {
28      success()
29    } else {
30      Err(format!("was {:?}", actual.borrow()))
31    }
32  }
33}
34
35pub fn matches_regex(regex: &str) -> MatchesRegex {
36  MatchesRegex {
37    regex: Regex::new(regex).unwrap(),
38  }
39}