renamer_rs/processor/
extractor.rs1use crate::Error::InvalidValue;
2use regex::Regex;
3
4#[derive(Debug, Clone)]
6pub struct Extractor {
7 #[allow(unused)]
8 name: Option<String>, pattern: Regex,
10}
11
12impl Extractor {
13 pub fn new(name: Option<String>, pattern: Regex) -> Self {
15 Self { name, pattern }
16 }
17
18 pub fn extract<S: AsRef<str>>(&self, value: S) -> Option<String> {
20 self.pattern
21 .find(value.as_ref())
22 .map(|m| m.as_str().to_string())
23 }
24}
25
26impl TryFrom<&[String]> for Extractor {
27 type Error = crate::error::Error;
28 fn try_from(value: &[String]) -> Result<Self, Self::Error> {
29 let pattern = match value.first() {
30 None => Err(InvalidValue(
31 "Extractor requires at least RegEx pattern".to_string(),
32 )),
33 Some(p) => Ok(Regex::new(p.as_str())?),
34 }?;
35 let name = value.get(1).cloned();
36
37 Ok(Self { name, pattern })
38 }
39}