public_api_rs/verify/
regex.rs

1use lazy_static::lazy_static;
2use regex::Regex;
3
4macro_rules! impl_regex {
5    ($re_name:ident,$re_str:expr) => {
6        /// 正则表达式验证
7        ///
8        #[doc = concat!("正则表达式:`", stringify!($re_str), "`")]
9        pub fn $re_name(text: &str) -> bool {
10            lazy_static! {
11                static ref RE: Regex = Regex::new($re_str).unwrap();
12            }
13            RE.is_match(text)
14        }
15    };
16}
17
18impl_regex!(is_url, r"[a-zA-z]+://[^\s]*");
19
20impl_regex!(
21    is_mail,
22    r"[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?"
23);
24
25impl_regex!(is_chinese, r"[\u4e00-\u9fa5]");
26
27impl_regex!(
28    is_phone,
29    r"^1(3\d|4[5-9]|5[0-35-9]|6[567]|7[0-8]|8\d|9[0-35-9])\d{8}$"
30);
31
32impl_regex!(
33    is_id_number,
34    r"^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9]|X)$"
35);
36
37impl_regex!(is_ipv4, r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}");
38
39impl_regex!(is_blank_line, r"^[\s&&[^\n]]*\n$");
40
41impl_regex!(is_blank, r"^\s*$");
42
43impl_regex!(is_number, r"\d+");
44
45#[cfg(test)]
46mod tests {
47    use super::*;
48
49    #[test]
50    fn test_verify() {
51        assert!(is_url("http://www.qq.com"));
52        assert!(is_mail("123@qq.com"));
53        assert!(is_chinese("中国"));
54        assert!(is_phone("13838383838"));
55        assert!(is_id_number("370283199001011234"));
56        assert!(is_ipv4("10.1.1.1"));
57        assert!(is_blank_line("   \r\n"));
58        assert!(is_blank("  \t  \n"));
59        assert!(is_number("123"));
60    }
61}