Expand description
matchable provides a convenient enum for checking if a piece of text is
matching a string or a regex.
use matchable::Matchable;
assert!(Matchable::Str("Abc".into()).is_match("Abc"));
assert!(!Matchable::Str("Abc".into()).is_match("abc"));
assert!(Matchable::Regex(regex::Regex::new("abc.").unwrap()).is_match("abcd"));More detail about the usage, please refer to doc of Matchable.
§Deserialization
One of the advantages of using this crate is deserialize into a Matchable.
This is often used as configuration, and allows user to pass a string or a regex as a pattern.
Here we use JSON as example:
If a string is enclosed with slashes (/), with or without optional flags as suffix,
this will be deserialized as a regex:
use matchable::Matchable;
let re_digits = serde_json::from_str::<Matchable>(r#""/\\d+/""#).unwrap();
assert!(re_digits.is_match("123"));
// with regex flags
let re_word = serde_json::from_str::<Matchable>(r#""/matchable/i""#).unwrap();
assert!(re_word.is_match("Matchable"));Otherwise, it will be parsed as a normal string as-is.
use matchable::Matchable;
let re1 = serde_json::from_str::<Matchable>(r#""/ab""#).unwrap();
assert!(re1.is_match("/ab"));
assert!(!re1.is_match("ab"));
let re2 = serde_json::from_str::<Matchable>(r#""ab/i""#).unwrap();
assert!(re2.is_match("ab/i"));
assert!(!re2.is_match("AB"));Structs§
- Regex
Only - This
RegexOnlyis just a wrapper ofRegex. UnlikeMatchable, thisRegExptreats the whole string as a regular expression, whileMatchableonly treats it as regular expression when it’s enclosed by/.
Enums§
- Matchable
Matchableis a wrapper for a plain string or a regex, and it’s used to check matching.