#regex #string #matching #enums #checking #piece #check

matchable

Check if text is matching against string or regex in one API

2 releases

0.1.1 Dec 19, 2022
0.1.0 Dec 19, 2022

#1335 in Text processing

30 downloads per month
Used in swc-react-remove-properti…

MIT license

12KB
201 lines

matchable

Crates.io docs.rs

matchable provides a convenient enum for checking if a piece of text is matching a string or a regex.

The common usage of this crate is used as configuration value type with serde feature enabled (disabled by default), then user can pass string and/or regex in just one enum. Later, you can use that enum to check if a piece of text is matching the string/regex or not.

Example

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

License

MIT License

Copyright (c) 2022-present Pig Fang


lib.rs:

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

Dependencies

~2.2–3.5MB
~58K SLoC