Skip to main content

renamer_rs/processor/
extractor.rs

1use crate::Error::InvalidValue;
2use regex::Regex;
3
4/// A struct to be used with the [`ProcessorBuilder`][crate::ProcessorBuilder] to select values from the original string value before segmentation
5#[derive(Debug, Clone)]
6pub struct Extractor {
7    #[allow(unused)]
8    name: Option<String>, // todo: use name/id in format string
9    pattern: Regex,
10}
11
12impl Extractor {
13    /// Create a new [`Extractor`]
14    pub fn new(name: Option<String>, pattern: Regex) -> Self {
15        Self { name, pattern }
16    }
17
18    /// Perform the matching on the provide value
19    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}