lang_interpreter/interpreter/
regex.rs

1use std::error;
2use std::fmt::{Display, Formatter};
3use regex::{Error, Regex};
4
5pub fn matches(text: &str, regex: &str) -> Result<bool, InvalidPatternSyntaxError> {
6    let regex = Regex::new(regex)?;
7
8    let match_result = regex.find(text);
9
10    Ok(match_result.is_some_and(|match_result| {
11        match_result.start() == 0 && match_result.end() == text.len()
12    }))
13}
14
15pub fn split(text: &str, regex: &str, limit: Option<usize>) -> Result<Vec<String>, InvalidPatternSyntaxError> {
16    let regex = Regex::new(regex)?;
17
18    let limit = limit.unwrap_or(0);
19    if limit == 0 {
20        let match_result = regex.split(text).map(|str| str.to_string());
21
22        let mut result = match_result.collect::<Vec<_>>();
23
24        //Remove trailing empty values
25        for i in (0..result.len()).rev() {
26            if !result[i].is_empty() {
27                break;
28            }
29
30            result.pop();
31        }
32
33        Ok(result)
34    }else {
35        let match_result = regex.splitn(text, limit).map(|str| str.to_string());
36
37        Ok(match_result.collect::<Vec<_>>())
38    }
39}
40
41pub fn replace(text: &str, regex: &str, replacement: String) -> Result<String, InvalidPatternSyntaxError> {
42    let regex = Regex::new(regex)?;
43
44    let match_result = regex.replace_all(text, replacement);
45
46    Ok(match_result.to_string())
47}
48
49#[derive(Debug)]
50pub struct InvalidPatternSyntaxError {
51    message: String
52}
53
54impl InvalidPatternSyntaxError {
55    pub fn new(message: impl Into<String>) -> Self {
56        Self {
57            message: message.into(),
58        }
59    }
60
61    pub fn message(&self) -> &str {
62        &self.message
63    }
64}
65
66impl Display for InvalidPatternSyntaxError {
67    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
68        f.write_str(&self.message)
69    }
70}
71
72impl error::Error for InvalidPatternSyntaxError {}
73
74impl From<Error> for InvalidPatternSyntaxError {
75    fn from(value: Error) -> Self {
76        Self {
77            message: value.to_string(),
78        }
79    }
80}