urlpattern/
regexp.rs

1use crate::parser::RegexSyntax;
2
3pub trait RegExp: Sized {
4  fn syntax() -> RegexSyntax;
5
6  /// Generates a regexp pattern for the given string. If the pattern is
7  /// invalid, the parse function should return an error.
8  fn parse(pattern: &str, flags: &str) -> Result<Self, ()>;
9
10  /// Matches the given text against the regular expression and returns the list
11  /// of captures. The matches are returned in the order they appear in the
12  /// regular expression. It is **not** prefixed with the full match. For groups
13  /// that occur in the regular expression, but did not match, the corresponding
14  /// capture should be `None`.
15  ///
16  /// Returns `None` if the text does not match the regular expression.
17  fn matches<'a>(&self, text: &'a str) -> Option<Vec<Option<&'a str>>>;
18}
19
20impl RegExp for regex::Regex {
21  fn syntax() -> RegexSyntax {
22    RegexSyntax::Rust
23  }
24
25  fn parse(pattern: &str, flags: &str) -> Result<Self, ()> {
26    regex::Regex::new(&format!("(?{flags}){pattern}")).map_err(|_| ())
27  }
28
29  fn matches<'a>(&self, text: &'a str) -> Option<Vec<Option<&'a str>>> {
30    let captures = self.captures(text)?;
31
32    let captures = captures
33      .iter()
34      .skip(1)
35      .map(|c| c.map(|m| m.as_str()))
36      .collect();
37
38    Some(captures)
39  }
40}