use ahash::AHashMap;
use regex::Regex;
#[derive(Debug, Clone)]
pub struct RegexCapture {
re: Regex,
}
impl RegexCapture {
pub fn new(value: &str) -> Result<Self, regex::Error> {
let re = Regex::new(value)?;
Ok(RegexCapture { re })
}
#[inline]
pub fn captures(
&self,
value: &str,
) -> (bool, Option<AHashMap<String, String>>) {
let Some(captures) = self.re.captures(value) else {
return (false, None);
};
let mut capture_variables = None;
for name in self.re.capture_names().flatten() {
if let Some(match_value) = captures.name(name) {
let values =
capture_variables.get_or_insert_with(AHashMap::new);
values
.insert(name.to_string(), match_value.as_str().to_string());
}
}
(true, capture_variables)
}
}
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn test_regex_capture() {
let re = RegexCapture::new(
r"(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})",
)
.unwrap();
let (matched, capture_variables) = re.captures("2024-03-14");
assert_eq!(true, matched);
let capture_variables = capture_variables.unwrap();
assert_eq!("2024", capture_variables.get("year").unwrap());
assert_eq!("03", capture_variables.get("month").unwrap());
assert_eq!("14", capture_variables.get("day").unwrap());
assert_eq!(3, capture_variables.len());
}
}