string_patterns/
pattern_replace.rs

1use regex::Error;
2use crate::utils::build_regex;
3use std::borrow::ToOwned;
4
5/// Core regular expression replacement methods 
6pub trait PatternReplace where Self:Sized {
7
8  /// Replace all matches of the pattern within a longer text with a boolean case_insensitive flag
9  /// NB: If the regex doesn't compile it will return an Error, otherwise in Ok result.
10  /// If the regex fails, nothing will be replaced
11  fn pattern_replace_result(&self, pattern: &str, replacement: &str,case_insensitive: bool) -> Result<Self, Error> where Self:Sized;
12
13  /// Replace only the first match of the pattern within a longer text with a boolean case_insensitive flag
14  /// NB: If the regex doesn't compile it will return an Error, otherwise in Ok result.
15  /// If the regex fails, nothing will be replaced
16  fn pattern_replace_first_result(&self, pattern: &str, replacement: &str,case_insensitive: bool) -> Result<Self, Error> where Self:Sized;
17
18  /// Replace all matches of the pattern within a longer text with a boolean case_insensitive flag
19  /// Returns a copy of the same data type. If the regex fails, nothing will be replaced.
20  fn pattern_replace(&self, pattern: &str, replacement: &str, case_insensitive: bool) -> Self where Self:Sized;
21
22
23  /// Replace only the first match of the pattern within a longer text with a boolean case_insensitive flag
24  /// Returns a copy of the same data type. If the regex fails, nothing will be replaced.
25  fn pattern_replace_first(&self, pattern: &str, replacement: &str, case_insensitive: bool) -> Self where Self:Sized;
26
27
28  /// Replace all matches of the pattern within a longer text in case-insensitive mode
29  /// If the regex fails, nothing will be replaced
30  fn pattern_replace_ci(&self, pattern: &str, replacement: &str) -> Self where Self:Sized {
31    self.pattern_replace(pattern, replacement, true)
32  }
33
34  /// Replace all matches of the pattern within a longer text in case-sensitive mode
35  /// If the regex fails, nothing will be replaced
36  fn pattern_replace_cs(&self, pattern: &str, replacement: &str) -> Self where Self:Sized {
37    self.pattern_replace(pattern, replacement, false)
38  }
39
40  /// Replace the first match only of the pattern within a longer text in case-insensitive mode
41  /// If the regex fails, nothing will be replaced
42  fn pattern_replace_first_ci(&self, pattern: &str, replacement: &str) -> Self where Self:Sized {
43    self.pattern_replace_first(pattern, replacement, true)
44  }
45
46  /// Replace the first match only of the pattern within a longer text in case-sensitive mode
47  /// If the regex fails, nothing will be replaced
48  fn pattern_replace_first_cs(&self, pattern: &str, replacement: &str) -> Self where Self:Sized {
49    self.pattern_replace_first(pattern, replacement, false)
50  }
51
52}
53
54/// Core regex replacement methods for Strings
55impl PatternReplace for String {
56
57  /// Regex-enabled replace method that will return an OK String result if successful and an error if the regex fails
58  fn pattern_replace_result(&self, pattern: &str, replacement: &str, case_insensitive: bool) -> Result<String, Error> {
59    match build_regex(pattern, case_insensitive) {
60      Ok(re) => Ok(re.replace_all(self, replacement).to_string()),
61      Err(error) => Err(error)
62    }
63  }
64
65  /// Regex-enabled replace method that will return an OK String result if successful and an error if the regex fails
66  fn pattern_replace_first_result(&self, pattern: &str, replacement: &str, case_insensitive: bool) -> Result<String, Error> {
67    match build_regex(pattern, case_insensitive) {
68      Ok(re) => Ok(re.replace(self, replacement).to_string()),
69      Err(error) => Err(error)
70    }
71  }
72
73  /// Simple regex-enabled replace-all method that will return the same string if the regex fails
74  fn pattern_replace(&self, pattern: &str, replacement: &str, case_insensitive: bool) -> String {
75    self.pattern_replace_result(pattern, replacement, case_insensitive).unwrap_or(self.to_owned())
76  }
77
78  /// Regex-enabled single replace method that will return an OK String result if successful and an error if the regex fails
79  fn pattern_replace_first(&self, pattern: &str, replacement: &str, case_insensitive: bool) -> String {
80    self.pattern_replace_first_result(pattern, replacement, case_insensitive).unwrap_or(self.to_owned())
81  }
82
83}
84
85/// Implemented separately of arrays / vectors of strings to ensure the regex is only compiled once
86impl PatternReplace for Vec<String> {
87  ///
88  /// Optional regex-enabled replace method that will return None if the regex fails
89  /// 
90  fn pattern_replace_result(&self, pattern: &str, replacement: &str, case_insensitive: bool) -> Result<Vec<String>, Error> {
91    match build_regex(pattern, case_insensitive) {
92      Ok(re) => {
93        let replacements = self.into_iter()
94            .map(|segment| re.replace_all(segment, replacement).to_string())
95            .collect::<Vec<String>>();
96        Ok(replacements)
97      },
98      Err(error) => Err(error)
99    }
100  }
101
102  ///
103  /// Optional regex-enabled replace method that will return None if the regex fails
104  /// 
105  fn pattern_replace_first_result(&self, pattern: &str, replacement: &str, case_insensitive: bool) -> Result<Vec<String>, Error> {
106    match build_regex(pattern, case_insensitive) {
107      Ok(re) => {
108        let replacements = self.into_iter()
109            .map(|segment| re.replace(segment, replacement).to_string())
110            .collect::<Vec<String>>();
111        Ok(replacements)
112      },
113      Err(error) => Err(error)
114    }
115  }
116
117  /// Simple regex-enabled replace-all method that will return the same string if the regex fails
118  fn pattern_replace(&self, pattern: &str, replacement: &str, case_insensitive: bool) -> Vec<String> {
119    self.pattern_replace_result(pattern, replacement, case_insensitive).unwrap_or(self.to_owned())
120  }
121
122  /// Simple regex-enabled replace-first method that will return the same string if the regex fails
123  fn pattern_replace_first(&self, pattern: &str, replacement: &str, case_insensitive: bool) -> Vec<String> {
124    self.pattern_replace_first_result(pattern, replacement, case_insensitive).unwrap_or(self.to_owned())
125  }
126
127}