string-patterns 0.4.0

Makes it easier to work with common string patterns and regular expressions in Rust, adding convenient regex match and replace methods (pattern_match and pattern_replace) to the standard String type as well to vectors of strings
Documentation
use crate::pattern_cache::with_cached_regex;
use crate::utils::build_whole_word_pattern;

/// Trait with methods to filter arrays or vectors of strings by regular expression patterns
/// Only pattern_filter() method needs to be implemented.
/// Both implementations ensure the regex is compiled only once.
/// If the regex fails, filters will not be applied.
pub trait PatternFilter<'a, T> where T:Sized {
  /// Filter an array of strs by the pattern
  fn pattern_filter(&'a self, pattern: &str, case_insensitive: bool) -> Vec<T>;

  /// Filters strings in case-insensitive mode
  fn pattern_filter_ci(&'a self, pattern: &str) -> Vec<T> {
    self.pattern_filter(pattern, true)
  }

  /// Filters strings in case-sensitive mode
  fn pattern_filter_cs(&'a self, pattern: &str) -> Vec<T> {
    self.pattern_filter(pattern, false)
  }

  /// Filters strings by whole word regex patterns with case-insensitive flag
  fn pattern_filter_word(&'a self, pattern: &str, case_insensitive: bool) -> Vec<T> {
    let word_pattern = build_whole_word_pattern(pattern);
    self.pattern_filter(&word_pattern, case_insensitive)
  }

  /// Filters strings by whole word regex patterns in case-insensitive mode
  fn pattern_filter_word_ci(&'a self, pattern: &str) -> Vec<T> {
    self.pattern_filter_word(pattern, true)
  }

  /// Filters strings by whole word regex patterns in case-sensitive mode
  fn pattern_filter_word_cs(&'a self, pattern: &str) -> Vec<T> {
    self.pattern_filter_word(pattern, false)
  }
}

/// Filter arrays or vectors of any string-like type (&str, String, etc.), returning a
/// Vec of the same element type.
impl<'a, T: AsRef<str> + Clone> PatternFilter<'a, T> for [T] {
  /// Filter an array of strs by the pattern
  fn pattern_filter(&'a self, pattern: &str, case_insensitive: bool) -> Vec<T> {
    with_cached_regex(pattern, case_insensitive, |re| {
      self.into_iter().filter(|s| re.is_match(s.as_ref())).map(|s| s.clone()).collect::<Vec<T>>()
    })
    .unwrap_or_else(|_| self.to_vec())
  }
}