derive_regex/
lib.rs

1pub use derive_regex_proc_macro::FromRegex;
2
3/// A trait for parsing types from a string using a regular expression
4///
5/// Derive this trait on a struct or enum to add the ability to parse it from a string using a regular expression.
6///
7/// Tuple-like structs or enum variants parse their fields from numbered regex capture groups, i.e. the groups must be defined in the same order as the fields.
8/// Named structs or enum variants use named capture groups with the same name as the fields, meaning their oreder doesn't matter.
9///
10/// The fields must be of a type that implements FromStr.
11///
12/// # Example
13///
14/// ```rust
15/// use derive_regex::FromRegex;
16///
17/// #[derive(Debug, FromRegex, PartialEq)]
18/// #[regex(pattern = r"(?P<name>\w+),\s*(?P<age>\d+)")]
19/// struct Person {
20///     name: String,
21///     age: u32,
22/// }
23///
24///     let input = "Alice, 30";
25///     let person = Person::parse(input).unwrap();
26///     assert_eq!(person, Person {
27///         name: "Alice".to_string(),
28///         age: 30,
29///     });
30/// ```
31pub trait FromRegex {
32    fn parse(input: &str) -> Result<Self, String>
33    where
34        Self: std::marker::Sized;
35}