[][src]Crate recap

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 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

Regex

A compiled regular expression for matching Unicode strings.

Functions

from_captures

Deserialize a type from named regex capture groups

Type Definitions

Error

A type which encapsulates recap errors