Crate recap[−][src]
Expand description
Recap deserializes structures from regex named capture groups extracted from strings.
You may find this crate useful for cases where input is provided as a raw string in a loosely structured format. A common use case for this is when you’re dealing with log file data that was not stored in a particular structed format like JSON but rather in a format that can be represented with a pattern.
Recap is provides what envy provides environment variables for named regex capture groups
Examples
Below is an example that derives a FromStr
for your type that will
parse into the struct using named capture groups
use recap::Recap;
use serde::Deserialize;
use std::error::Error;
#[derive(Debug, Deserialize, PartialEq, Recap)]
#[recap(regex=r#"(?P<foo>\S+)\s(?P<bar>\S+)"#)]
struct Example {
foo: String,
bar: String,
}
fn main() -> Result<(), Box<dyn Error>> {
assert_eq!(
"hello there".parse::<Example>()?,
Example {
foo: "hello".into(),
bar: "there".into()
}
);
Ok(())
}
You can also use Recap with Serde’s zero-copy deserialization:
use recap::Recap;
use serde::Deserialize;
use std::convert::TryInto;
use std::error::Error;
#[derive(Debug, Deserialize, PartialEq, Recap)]
#[recap(regex=r#"(?P<foo>\S+)\s(?P<bar>\S+)"#)]
struct Example<'a> {
foo: &'a str,
bar: &'a str,
}
fn main() -> Result<(), Box<dyn Error>> {
let input = "hello there";
let result: Example = input.try_into()?;
assert_eq!(
result,
Example {
foo: "hello",
bar: "there"
}
);
Ok(())
}
You can also use recap by using the generic function from_captures
in which
case you’ll be reponsible for bringing your only Regex reference.
💡 For convenience the regex crate’s Regex
type is re-exported
use recap::{Regex, from_captures};
use serde::Deserialize;
use std::error::Error;
#[derive(Debug, Deserialize, PartialEq)]
struct Example {
foo: String,
bar: String,
}
fn main() -> Result<(), Box<dyn Error>> {
let pattern = Regex::new(
r#"(?P<foo>\S+)\s(?P<bar>\S+)"#
)?;
let example: Example = from_captures(
&pattern, "hello there"
)?;
assert_eq!(
example,
Example {
foo: "hello".into(),
bar: "there".into()
}
);
Ok(())
}
Structs
A compiled regular expression for matching Unicode strings.
Functions
Deserialize a type from named regex capture groups
Type Definitions
A type which encapsulates recap errors