is_url/lib.rs
1/*
2| MIT License
3|
4| Copyright (c) 2022 Mauro Baladés
5|
6| Permission is hereby granted, free of charge, to any person obtaining a copy
7| of this software and associated documentation files (the "Software"), to deal
8| in the Software without restriction, including without limitation the rights
9| to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10| copies of the Software, and to permit persons to whom the Software is
11| furnished to do so, subject to the following conditions:
12|
13| The above copyright notice and this permission notice shall be included in all
14| copies or substantial portions of the Software.
15|
16| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17| IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18| FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19| AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20| LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21| OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22| SOFTWARE.
23*/
24
25#[macro_use]
26extern crate lazy_static;
27
28use regex::Regex;
29
30const URL_REGEX: &str =
31 r"https?://(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)";
32
33lazy_static! {
34 static ref RE: Regex = {
35 Regex::new(URL_REGEX).unwrap()
36 };
37}
38
39pub fn is_url(url: &str) -> bool {
40 return RE.is_match(url);
41}
42
43#[cfg(test)]
44mod tests {
45 use crate::is_url;
46
47 #[test]
48 fn normal_url() {
49 assert!(is_url("https://hello.com"));
50 }
51
52 #[test]
53 fn url_path() {
54 assert!(is_url("https://hello.com/example"));
55 }
56
57 #[test]
58 fn url_section() {
59 assert!(is_url("https://hello.com#example"));
60 }
61
62 #[test]
63 fn url_arguments() {
64 assert!(is_url("https://hello.com?q=hello"));
65 }
66}