Skip to main content

shacl_ir/components/
pattern.rs

1use crate::compiled_shacl_error::CompiledShaclError;
2use rudof_rdf::rdf_core::utils::RDFRegex;
3use std::fmt::Display;
4
5/// sh:property can be used to specify that each value node has a given property
6/// shape.
7///
8/// https://www.w3.org/TR/shacl/#PropertyShapeComponent
9#[derive(Debug, Clone)]
10pub struct Pattern {
11    pattern: String,
12    flags: Option<String>,
13    regex: RDFRegex,
14}
15
16impl Pattern {
17    pub fn new(pattern: String, flags: Option<String>) -> Result<Self, Box<CompiledShaclError>> {
18        let regex = RDFRegex::new(&pattern, flags.as_deref()).map_err(|e| CompiledShaclError::InvalidRegex {
19            pattern: pattern.clone(),
20            flags: flags.clone(),
21            error: Box::new(e),
22        })?;
23        Ok(Pattern { pattern, flags, regex })
24    }
25
26    pub fn pattern(&self) -> &String {
27        &self.pattern
28    }
29
30    pub fn flags(&self) -> &Option<String> {
31        &self.flags
32    }
33
34    pub fn regex(&self) -> &RDFRegex {
35        &self.regex
36    }
37
38    pub fn match_str(&self, str: &str) -> bool {
39        self.regex().is_match(str)
40    }
41}
42
43impl Display for Pattern {
44    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
45        if let Some(flags) = &self.flags {
46            write!(f, "Pattern: /{}/{}", self.pattern(), flags)
47        } else {
48            write!(f, "Pattern: /{}/", self.pattern())
49        }
50    }
51}