| 1 | //! Match strings against a simple wildcard pattern. |
| 2 | //! Tests a wildcard pattern `p` against an input string `s`. Returns true only when `p` matches the entirety of `s`. |
| 3 | //! |
| 4 | //! See also the example described on [wikipedia](https://en.wikipedia.org/wiki/Matching_wildcards) for matching wildcards. |
| 5 | //! |
| 6 | //! No escape characters are defined. |
| 7 | //! |
| 8 | //! - `?` matches exactly one occurrence of any character. |
| 9 | //! - `*` matches arbitrary many (including zero) occurrences of any character. |
| 10 | //! |
| 11 | //! Examples matching wildcards: |
| 12 | //! ``` rust |
| 13 | //! # extern crate wildmatch; use wildmatch::WildMatch; |
| 14 | //! assert!(WildMatch::new("cat").matches("cat")); |
| 15 | //! assert!(WildMatch::new("*cat*").matches("dog_cat_dog")); |
| 16 | //! assert!(WildMatch::new("c?t").matches("cat")); |
| 17 | //! assert!(WildMatch::new("c?t").matches("cot")); |
| 18 | //! ``` |
| 19 | //! Examples not matching wildcards: |
| 20 | //! ``` rust |
| 21 | //! # extern crate wildmatch; use wildmatch::WildMatch; |
| 22 | //! assert!(!WildMatch::new("dog").matches("cat")); |
| 23 | //! assert!(!WildMatch::new("*d").matches("cat")); |
| 24 | //! assert!(!WildMatch::new("????").matches("cat")); |
| 25 | //! assert!(!WildMatch::new("?").matches("cat")); |
| 26 | //! ``` |
| 27 | //! |
| 28 | //! You can specify custom `char` values for the single and multi-character |
| 29 | //! wildcards. For example, to use `%` as the multi-character wildcard and |
| 30 | //! `_` as the single-character wildcard: |
| 31 | //! ```rust |
| 32 | //! # extern crate wildmatch; use wildmatch::WildMatchPattern; |
| 33 | //! assert!(WildMatchPattern::<'%', '_'>::new("%cat%").matches("dog_cat_dog")); |
| 34 | //! ``` |
| 35 | |
| 36 | use std::fmt; |
| 37 | |
| 38 | #[cfg(feature = "serde")] |
| 39 | use serde::{Deserialize, Serialize}; |
| 40 | |
| 41 | /// A wildcard matcher using `*` as the multi-character wildcard and `?` as |
| 42 | /// the single-character wildcard. |
| 43 | pub type WildMatch = WildMatchPattern<'*', '?'>; |
| 44 | |
| 45 | /// Wildcard matcher used to match strings. |
| 46 | /// |
| 47 | /// `MULTI_WILDCARD` is the character used to represent a |
| 48 | /// multiple-character wildcard (e.g., `*`), and `SINGLE_WILDCARD` is the |
| 49 | /// character used to represent a single-character wildcard (e.g., `?`). |
| 50 | /// |
| 51 | /// # Panics |
| 52 | /// |
| 53 | /// Panics at compile time if both wildcard characters are identical. |
| 54 | /// |
| 55 | /// # Examples |
| 56 | /// |
| 57 | /// ```compile_fail |
| 58 | /// # use wildmatch::WildMatchPattern; |
| 59 | /// // ❌ Fails to compile: '*' cannot be both wildcards. |
| 60 | /// WildMatchPattern::<'*', '*'>::new(""); |
| 61 | /// ``` |
| 62 | /// |
| 63 | /// ```compile_fail |
| 64 | /// # use wildmatch::WildMatchPattern; |
| 65 | /// // ❌ Fails to compile: '*' cannot be both wildcards. |
| 66 | /// WildMatchPattern::<'*', '*'>::new_case_insensitive(""); |
| 67 | /// ``` |
| 68 | /// |
| 69 | /// ``` |
| 70 | /// # use wildmatch::WildMatchPattern; |
| 71 | /// // ✅ Compiles fine. |
| 72 | /// WildMatchPattern::<'*', '?'>::new(""); |
| 73 | /// ``` |
| 74 | /// |
| 75 | /// ``` |
| 76 | /// # use wildmatch::WildMatchPattern; |
| 77 | /// // ✅ Compiles fine. |
| 78 | /// WildMatchPattern::<'*', '?'>::new_case_insensitive(""); |
| 79 | /// ``` |
| 80 | #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] |
| 81 | #[derive(Debug, Clone, PartialEq, PartialOrd, Default)] |
| 82 | pub struct WildMatchPattern<const MULTI_WILDCARD: char, const SINGLE_WILDCARD: char> { |
| 83 | pattern: Vec<char>, |
| 84 | case_insensitive: bool, |
| 85 | } |
| 86 | |
| 87 | impl<const MULTI_WILDCARD: char, const SINGLE_WILDCARD: char> fmt::Display |
| 88 | for WildMatchPattern<MULTI_WILDCARD, SINGLE_WILDCARD> |
| 89 | { |
| 90 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 91 | use std::fmt::Write; |
| 92 | for c in &self.pattern { |
| 93 | f.write_char(*c)?; |
| 94 | } |
| 95 | Ok(()) |
| 96 | } |
| 97 | } |
| 98 | |
| 99 | impl<const MULTI_WILDCARD: char, const SINGLE_WILDCARD: char> |
| 100 | WildMatchPattern<MULTI_WILDCARD, SINGLE_WILDCARD> |
| 101 | { |
| 102 | const WILDCARDS_DIFFER: () = assert!( |
| 103 | MULTI_WILDCARD != SINGLE_WILDCARD, |
| 104 | "single and multi wildcards cannot be the same" |
| 105 | ); |
| 106 | |
| 107 | /// Constructor with pattern which can be used for matching. |
| 108 | pub fn new(pattern: &str) -> WildMatchPattern<MULTI_WILDCARD, SINGLE_WILDCARD> { |
| 109 | #[allow(clippy::let_unit_value)] |
| 110 | let _ = Self::WILDCARDS_DIFFER; |
| 111 | |
| 112 | let mut simplified: Vec<char> = pattern.chars().collect(); |
| 113 | let mut new_len = simplified.len(); |
| 114 | let mut wildcard_count = 0; |
| 115 | |
| 116 | for idx in (0..simplified.len()).rev() { |
| 117 | if simplified[idx] == MULTI_WILDCARD { |
| 118 | wildcard_count += 1; |
| 119 | } else { |
| 120 | if wildcard_count > 1 { |
| 121 | new_len -= wildcard_count - 1; |
| 122 | simplified[idx + 1..].rotate_left(wildcard_count - 1); |
| 123 | } |
| 124 | wildcard_count = 0; |
| 125 | } |
| 126 | } |
| 127 | if wildcard_count > 1 { |
| 128 | new_len -= wildcard_count - 1; |
| 129 | simplified.rotate_left(wildcard_count - 1); |
| 130 | } |
| 131 | |
| 132 | simplified.truncate(new_len); |
| 133 | |
| 134 | Self { |
| 135 | pattern: simplified, |
| 136 | case_insensitive: false, |
| 137 | } |
| 138 | } |
| 139 | |
| 140 | /// Constructor with pattern which can be used for matching with case-insensitive comparison. |
| 141 | pub fn new_case_insensitive( |
| 142 | pattern: &str, |
| 143 | ) -> WildMatchPattern<MULTI_WILDCARD, SINGLE_WILDCARD> { |
| 144 | let mut m = Self::new(pattern); |
| 145 | m.case_insensitive = true; |
| 146 | m |
| 147 | } |
| 148 | |
| 149 | #[deprecated(since = "2.0.0", note = "use `matches` instead")] |
| 150 | pub fn is_match(&self, input: &str) -> bool { |
| 151 | self.matches(input) |
| 152 | } |
| 153 | |
| 154 | /// Returns true if pattern applies to the given input string |
| 155 | pub fn matches(&self, input: &str) -> bool { |
| 156 | if self.pattern.is_empty() { |
| 157 | return input.is_empty(); |
| 158 | } |
| 159 | let mut input_chars = input.chars(); |
| 160 | |
| 161 | let mut pattern_idx = 0; |
| 162 | if let Some(mut input_char) = input_chars.next() { |
| 163 | const NONE: usize = usize::MAX; |
| 164 | let mut start_idx = NONE; |
| 165 | let mut matched = "".chars(); |
| 166 | |
| 167 | loop { |
| 168 | if pattern_idx < self.pattern.len() && self.pattern[pattern_idx] == MULTI_WILDCARD { |
| 169 | start_idx = pattern_idx; |
| 170 | matched = input_chars.clone(); |
| 171 | pattern_idx += 1; |
| 172 | } else if pattern_idx < self.pattern.len() |
| 173 | && (self.pattern[pattern_idx] == SINGLE_WILDCARD |
| 174 | || self.pattern[pattern_idx] == input_char |
| 175 | || (self.case_insensitive |
| 176 | && self.pattern[pattern_idx].to_lowercase().collect::<Vec<_>>() |
| 177 | == input_char.to_lowercase().collect::<Vec<_>>())) |
| 178 | { |
| 179 | pattern_idx += 1; |
| 180 | if let Some(next_char) = input_chars.next() { |
| 181 | input_char = next_char; |
| 182 | } else { |
| 183 | break; |
| 184 | } |
| 185 | } else if start_idx != NONE { |
| 186 | pattern_idx = start_idx + 1; |
| 187 | if let Some(next_char) = matched.next() { |
| 188 | input_char = next_char; |
| 189 | } else { |
| 190 | break; |
| 191 | } |
| 192 | input_chars = matched.clone(); |
| 193 | } else { |
| 194 | return false; |
| 195 | } |
| 196 | } |
| 197 | } |
| 198 | |
| 199 | while pattern_idx < self.pattern.len() && self.pattern[pattern_idx] == MULTI_WILDCARD { |
| 200 | pattern_idx += 1; |
| 201 | } |
| 202 | |
| 203 | // If we have reached the end of both the pattern and the text, the pattern matches the text. |
| 204 | pattern_idx == self.pattern.len() |
| 205 | } |
| 206 | |
| 207 | /// Returns the pattern string. |
| 208 | /// N.B. Consecutive multi-wildcards are simplified to a single multi-wildcard. |
| 209 | pub fn pattern(&self) -> String { |
| 210 | self.pattern.iter().collect::<String>() |
| 211 | } |
| 212 | |
| 213 | /// Returns the pattern string as a slice of chars. |
| 214 | pub fn pattern_chars(&self) -> &[char] { |
| 215 | &self.pattern |
| 216 | } |
| 217 | |
| 218 | /// Returns if the pattern is case-insensitive. |
| 219 | pub fn is_case_insensitive(&self) -> bool { |
| 220 | self.case_insensitive |
| 221 | } |
| 222 | } |
| 223 | |
| 224 | impl<'a, const MULTI_WILDCARD: char, const SINGLE_WILDCARD: char> PartialEq<&'a str> |
| 225 | for WildMatchPattern<MULTI_WILDCARD, SINGLE_WILDCARD> |
| 226 | { |
| 227 | fn eq(&self, &other: &&'a str) -> bool { |
| 228 | self.matches(other) |
| 229 | } |
| 230 | } |
| 231 | |
| 232 | #[cfg(test)] |
| 233 | mod tests { |
| 234 | use super::*; |
| 235 | use ntest::assert_false; |
| 236 | use ntest::test_case; |
| 237 | use rand::{distributions::Alphanumeric, Rng}; |
| 238 | |
| 239 | #[test] |
| 240 | fn is_match_random() { |
| 241 | const PATTERN_LEN: usize = 100; |
| 242 | |
| 243 | for _ in 0..1_000 { |
| 244 | let mut rng = rand::thread_rng(); |
| 245 | let mut pattern: String = rand::thread_rng() |
| 246 | .sample_iter(&Alphanumeric) |
| 247 | .take(PATTERN_LEN) |
| 248 | .map(char::from) |
| 249 | .collect(); |
| 250 | for _ in 0..rng.gen_range(0..15) { |
| 251 | let idx = rng.gen_range(0..PATTERN_LEN); |
| 252 | pattern.replace_range(idx..idx + 1, "?") |
| 253 | } |
| 254 | for _ in 0..rng.gen_range(0..15) { |
| 255 | let idx = rng.gen_range(0..PATTERN_LEN); |
| 256 | pattern.replace_range(idx..idx + 1, "*") |
| 257 | } |
| 258 | let m = WildMatch::new(&pattern); |
| 259 | for pattern_idx in 0..rng.gen_range(0..1_000) { |
| 260 | let mut input = pattern.clone(); |
| 261 | for (i, c) in pattern.chars().rev().enumerate() { |
| 262 | let idx = pattern.len() - i - 1; |
| 263 | if c == '?' { |
| 264 | let rand_char: String = rand::thread_rng() |
| 265 | .sample_iter(&Alphanumeric) |
| 266 | .take(1) |
| 267 | .map(char::from) |
| 268 | .collect(); |
| 269 | input.replace_range(idx..idx + 1, &rand_char) |
| 270 | } |
| 271 | if c == '*' { |
| 272 | let rand_char: String = rand::thread_rng() |
| 273 | .sample_iter(&Alphanumeric) |
| 274 | .take(rng.gen_range(0..15)) |
| 275 | .map(char::from) |
| 276 | .collect(); |
| 277 | input.replace_range(idx..idx + 1, &rand_char) |
| 278 | } |
| 279 | } |
| 280 | assert!( |
| 281 | m.matches(&input), |
| 282 | "Pattern ({}): {} doesn't match input: {}", |
| 283 | pattern_idx, |
| 284 | pattern, |
| 285 | input |
| 286 | ); |
| 287 | } |
| 288 | } |
| 289 | } |
| 290 | |
| 291 | #[test_case("**")] |
| 292 | #[test_case("*")] |
| 293 | #[test_case("*?*")] |
| 294 | #[test_case("c*")] |
| 295 | #[test_case("c?*")] |
| 296 | #[test_case("???")] |
| 297 | #[test_case("c?t")] |
| 298 | #[test_case("cat")] |
| 299 | #[test_case("*cat")] |
| 300 | #[test_case("cat*")] |
| 301 | fn is_match(pattern: &str) { |
| 302 | let m = WildMatch::new(pattern); |
| 303 | assert!(m.matches("cat")); |
| 304 | } |
| 305 | |
| 306 | #[test_case("CAT", "cat")] |
| 307 | #[test_case("CAT", "CAT")] |
| 308 | #[test_case("CA?", "Cat")] |
| 309 | #[test_case("C*", "cAt")] |
| 310 | #[test_case("C?*", "cAT")] |
| 311 | #[test_case("C**", "caT")] |
| 312 | #[test_case("КОТ", "кот", name = "cyrillic_lower")] |
| 313 | #[test_case("КОТ", "КОТ", name = "cyrillic_upper")] |
| 314 | #[test_case("КО?", "Кот", name = "cyrillic_mixed1")] |
| 315 | #[test_case("К*", "кОт", name = "cyrillic_mixed2")] |
| 316 | #[test_case("К?*", "кОТ", name = "cyrillic_mixed3")] |
| 317 | #[test_case("К**", "коТ", name = "cyrillic_mixed4")] |
| 318 | fn is_match_case_insensitive(pattern: &str, input: &str) { |
| 319 | let m = WildMatch::new_case_insensitive(pattern); |
| 320 | assert!(m.matches(input)); |
| 321 | } |
| 322 | |
| 323 | #[test_case("*d*")] |
| 324 | #[test_case("*d")] |
| 325 | #[test_case("d*")] |
| 326 | #[test_case("*c")] |
| 327 | #[test_case("?")] |
| 328 | #[test_case("??")] |
| 329 | #[test_case("????")] |
| 330 | #[test_case("?????")] |
| 331 | #[test_case("*????")] |
| 332 | #[test_case("cats")] |
| 333 | #[test_case("cat?")] |
| 334 | #[test_case("cacat")] |
| 335 | #[test_case("cat*dog")] |
| 336 | #[test_case("CAT")] |
| 337 | fn no_match(pattern: &str) { |
| 338 | let m = WildMatch::new(pattern); |
| 339 | assert_false!(m.matches("cat")); |
| 340 | } |
| 341 | |
| 342 | #[test_case("1", "")] |
| 343 | #[test_case("?", "")] |
| 344 | #[test_case("?", "11")] |
| 345 | #[test_case("*1?", "123")] |
| 346 | #[test_case("*12", "122")] |
| 347 | #[test_case("cat?", "wildcats")] |
| 348 | #[test_case("cat*", "wildcats")] |
| 349 | #[test_case("*x*", "wildcats")] |
| 350 | #[test_case("*a", "wildcats")] |
| 351 | #[test_case("", "wildcats")] |
| 352 | #[test_case(" ", "wildcats")] |
| 353 | #[test_case(" ", "\n")] |
| 354 | #[test_case(" ", "\t", name = "whitespaceMismatch")] |
| 355 | #[test_case("???", "wildcats")] |
| 356 | fn no_match_long(pattern: &str, expected: &str) { |
| 357 | let m = WildMatch::new(pattern); |
| 358 | assert_false!(m.matches(expected)) |
| 359 | } |
| 360 | |
| 361 | #[test_case("*", "")] |
| 362 | #[test_case("*", "1")] |
| 363 | #[test_case("?", "1")] |
| 364 | #[test_case("*121", "12121")] |
| 365 | #[test_case("?*3", "111333")] |
| 366 | #[test_case("*113", "1113")] |
| 367 | #[test_case("*113", "113")] |
| 368 | #[test_case("*113", "11113")] |
| 369 | #[test_case("*113", "111113")] |
| 370 | #[test_case("*???a", "bbbba")] |
| 371 | #[test_case("*???a", "bbbbba")] |
| 372 | #[test_case("*???a", "bbbbbba")] |
| 373 | #[test_case("*o?a*", "foobar")] |
| 374 | #[test_case("*ooo?ar", "foooobar")] |
| 375 | #[test_case("*o?a*r", "foobar")] |
| 376 | #[test_case("*cat*", "d&(*og_cat_dog")] |
| 377 | #[test_case("*?*", "d&(*og_cat_dog")] |
| 378 | #[test_case("*a*", "d&(*og_cat_dog")] |
| 379 | #[test_case("a*b", "a*xb")] |
| 380 | #[test_case("*", "*")] |
| 381 | #[test_case("*", "?")] |
| 382 | #[test_case("?", "?")] |
| 383 | #[test_case("wildcats", "wildcats")] |
| 384 | #[test_case("wild*cats", "wild?cats")] |
| 385 | #[test_case("wi*ca*s", "wildcats")] |
| 386 | #[test_case("wi*ca?s", "wildcats")] |
| 387 | #[test_case("*o?", "hog_cat_dog")] |
| 388 | #[test_case("*o?", "cat_dog")] |
| 389 | #[test_case("*at_dog", "cat_dog")] |
| 390 | #[test_case(" ", " ")] |
| 391 | #[test_case("* ", "\n ")] |
| 392 | #[test_case("\n", "\n", name = "special_chars")] |
| 393 | #[test_case("*32", "432")] |
| 394 | #[test_case("*32", "332")] |
| 395 | #[test_case("*332", "332")] |
| 396 | #[test_case("*32", "32")] |
| 397 | #[test_case("*32", "3232")] |
| 398 | #[test_case("*32", "3232332")] |
| 399 | #[test_case("*?2", "332")] |
| 400 | #[test_case("*?2", "3332")] |
| 401 | #[test_case("33*", "333")] |
| 402 | #[test_case("da*da*da*", "daaadabadmanda")] |
| 403 | #[test_case("*?", "xx")] |
| 404 | fn match_long(pattern: &str, expected: &str) { |
| 405 | let m = WildMatch::new(pattern); |
| 406 | assert!( |
| 407 | m.matches(expected), |
| 408 | "Expected pattern {} to match {}", |
| 409 | pattern, |
| 410 | expected |
| 411 | ); |
| 412 | } |
| 413 | |
| 414 | #[test] |
| 415 | fn complex_pattern() { |
| 416 | const TEXT: &str = "Lorem ipsum dolor sit amet, \ |
| 417 | consetetur sadipscing elitr, sed diam nonumy eirmod tempor \ |
| 418 | invidunt ut labore et dolore magna aliquyam erat, sed diam \ |
| 419 | voluptua. At vero eos et accusam et justo duo dolores et ea \ |
| 420 | rebum. Stet clita kasd gubergren, no sea takimata sanctus est \ |
| 421 | Lorem ipsum dolor sit amet."; |
| 422 | const COMPLEX_PATTERN: &str = "Lorem?ipsum*dolore*ea* ?????ata*."; |
| 423 | let m = WildMatch::new(COMPLEX_PATTERN); |
| 424 | assert!(m.matches(TEXT)); |
| 425 | } |
| 426 | |
| 427 | #[test] |
| 428 | fn complex_pattern_alternative_wildcards() { |
| 429 | const TEXT: &str = "Lorem ipsum dolor sit amet, \ |
| 430 | consetetur sadipscing elitr, sed diam nonumy eirmod tempor \ |
| 431 | invidunt ut labore et dolore magna aliquyam erat, sed diam \ |
| 432 | voluptua. At vero eos et accusam et justo duo dolores et ea \ |
| 433 | rebum. Stet clita kasd gubergren, no sea takimata sanctus est \ |
| 434 | Lorem ipsum dolor sit amet."; |
| 435 | const COMPLEX_PATTERN: &str = "Lorem_ipsum%dolore%ea% _____ata%."; |
| 436 | let m = WildMatchPattern::<'%', '_'>::new(COMPLEX_PATTERN); |
| 437 | assert!(m.matches(TEXT)); |
| 438 | } |
| 439 | |
| 440 | #[test] |
| 441 | fn compare_via_equal() { |
| 442 | let m = WildMatch::new("c?*"); |
| 443 | assert!(m == "cat"); |
| 444 | assert!(m == "car"); |
| 445 | assert!(m != "dog"); |
| 446 | } |
| 447 | |
| 448 | #[test] |
| 449 | fn compare_empty() { |
| 450 | let m: WildMatch = WildMatch::new(""); |
| 451 | assert!(m != "bar"); |
| 452 | assert!(m == ""); |
| 453 | } |
| 454 | |
| 455 | #[test] |
| 456 | fn compare_default() { |
| 457 | let m: WildMatch = Default::default(); |
| 458 | assert!(m == ""); |
| 459 | assert!(m != "bar"); |
| 460 | } |
| 461 | |
| 462 | #[test] |
| 463 | fn compare_wild_match() { |
| 464 | assert_eq!(WildMatch::default(), WildMatch::new("")); |
| 465 | assert_eq!(WildMatch::new("abc"), WildMatch::new("abc")); |
| 466 | assert_eq!(WildMatch::new("a*bc"), WildMatch::new("a*bc")); |
| 467 | assert_ne!(WildMatch::new("abc"), WildMatch::new("a*bc")); |
| 468 | assert_ne!(WildMatch::new("a*bc"), WildMatch::new("a?bc")); |
| 469 | assert_eq!(WildMatch::new("a***c"), WildMatch::new("a*c")); |
| 470 | } |
| 471 | |
| 472 | #[test] |
| 473 | fn print_string() { |
| 474 | let m = WildMatch::new("Foo/Bar"); |
| 475 | assert_eq!("Foo/Bar", m.to_string()); |
| 476 | } |
| 477 | |
| 478 | #[test] |
| 479 | fn to_string_f() { |
| 480 | let m = WildMatch::new("F"); |
| 481 | assert_eq!("F", m.to_string()); |
| 482 | } |
| 483 | |
| 484 | #[test] |
| 485 | fn to_string_with_star() { |
| 486 | assert_eq!("a*bc", WildMatch::new("a*bc").to_string()); |
| 487 | assert_eq!("a*bc", WildMatch::new("a**bc").to_string()); |
| 488 | assert_eq!("a*bc*", WildMatch::new("a*bc*").to_string()); |
| 489 | } |
| 490 | |
| 491 | #[test] |
| 492 | fn to_string_with_question_sign() { |
| 493 | assert_eq!("a?bc", WildMatch::new("a?bc").to_string()); |
| 494 | assert_eq!("a??bc", WildMatch::new("a??bc").to_string()); |
| 495 | } |
| 496 | |
| 497 | #[test] |
| 498 | fn to_string_empty() { |
| 499 | let m = WildMatch::new(""); |
| 500 | assert_eq!("", m.to_string()); |
| 501 | } |
| 502 | } |