Skip to main content

teaql_tool_std/
regex.rs

1use ::regex::Regex;
2use teaql_tool_core::{Result, TeaQLToolError};
3
4pub struct RegexTool;
5
6impl RegexTool {
7    pub fn new() -> Self {
8        Self
9    }
10
11    fn compile(&self, pattern: &str) -> Result<Regex> {
12        Regex::new(pattern)
13            .map_err(|e| TeaQLToolError::InvalidArgument(format!("Invalid regex: {}", e)))
14    }
15
16    pub fn is_match(&self, pattern: &str, text: &str) -> Result<bool> {
17        let re = self.compile(pattern)?;
18        Ok(re.is_match(text))
19    }
20
21    pub fn find(&self, pattern: &str, text: &str) -> Result<Option<String>> {
22        let re = self.compile(pattern)?;
23        Ok(re.find(text).map(|m| m.as_str().to_string()))
24    }
25
26    pub fn find_all(&self, pattern: &str, text: &str) -> Result<Vec<String>> {
27        let re = self.compile(pattern)?;
28        Ok(re.find_iter(text).map(|m| m.as_str().to_string()).collect())
29    }
30
31    pub fn replace(&self, pattern: &str, text: &str, rep: &str) -> Result<String> {
32        let re = self.compile(pattern)?;
33        Ok(re.replace(text, rep).into_owned())
34    }
35
36    pub fn replace_all(&self, pattern: &str, text: &str, rep: &str) -> Result<String> {
37        let re = self.compile(pattern)?;
38        Ok(re.replace_all(text, rep).into_owned())
39    }
40
41    pub fn split(&self, pattern: &str, text: &str) -> Result<Vec<String>> {
42        let re = self.compile(pattern)?;
43        Ok(re.split(text).map(|s| s.to_string()).collect())
44    }
45
46    pub fn escape(&self, text: &str) -> String {
47        ::regex::escape(text)
48    }
49
50    pub fn validate(&self, pattern: &str) -> bool {
51        Regex::new(pattern).is_ok()
52    }
53}
54
55impl Default for RegexTool {
56    fn default() -> Self {
57        Self::new()
58    }
59}