1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
use regex::Regex;
use std::{borrow::Cow, convert::Infallible};
use super::TransformField;
use crate::{action::transform::result::TransformResult, error::BadRegexError};
pub const HTML_TAG_RE: &str = "<[^>]*>";
#[derive(Debug)]
pub struct Replace {
re: Regex,
with: String,
}
impl Replace {
pub fn new(re: &str, with: String) -> Result<Self, BadRegexError> {
Ok(Self {
re: Regex::new(re)?,
with,
})
}
}
impl TransformField for Replace {
type Err = Infallible;
fn transform_field(&self, old_val: Option<&str>) -> Result<TransformResult<String>, Self::Err> {
Ok(TransformResult::New(old_val.map(|old| {
self.re.replace_all(old, &self.with).into_owned()
})))
}
}
impl Replace {
#[must_use]
pub fn replace<'a>(&self, text: &'a str) -> Cow<'a, str> {
self.re.replace_all(text, &self.with)
}
}