Crate regex_captures

source ·
Expand description

regex_captures makes it easier to work with capture groups when using the regex crate.

Debugging and type conversions using the regex API can be cumbersome, this crate aims to help with this.

All operations are fallible since we do not guarantee that the requested capture groups exist in the supplied regex.

Error-reporting is prioritized over performance. Using this crate when there are a lot expected failures in matching or parsing leads to extra allocations.

Table of methods:

methodcapture_typeconversiontotal?
getnumericFrom<str>yes
parse_getnumericFromStrno
try_getnumericTryFrom<str>no
namenamedFrom<str>yes
parse_namenamedFromStrno
try_namenamedTryFrom<str>no

Examples using all methods:

use lazy_regex::regex;
use regex_captures::{Captures, Result};

#[derive(Debug, PartialEq, Eq)]
struct Components {
    prefix: bool,
    infixes: String,
    suffix: Number,
}

#[derive(Debug, PartialEq, Eq)]
struct Number(usize);
impl<'a> TryFrom<&'a str> for Number {
    type Error = std::num::ParseIntError;
    fn try_from(s: &'a str) -> Result<Self, Self::Error> {
        Ok(Number(s.parse()?))
    }
}

fn main() -> Result<()> {
    let numeric = Captures::new(regex!("^(true|false):(.+):([^:]+)$"), "true:two:three:4")?;
    let result = Components {
        prefix: numeric.parse_get(1)?,
        infixes: numeric.get(2)?,
        suffix: numeric.try_get(3)?,
    };
    assert_eq!(
        result,
        Components {
            prefix: true,
            infixes: "two:three".to_owned(),
            suffix: Number(4),
        }
    );

    let named = Captures::new(
        regex!("^(?<prefix>true|false):(?<infixes>.+):(?<suffix>[^:]+)$"),
        "true:two:three:4",
    )?;
    let result = Components {
        prefix: named.parse_name("prefix")?,
        infixes: named.name("infixes")?,
        suffix: named.try_name("suffix")?,
    };
    assert_eq!(
        result,
        Components {
            prefix: true,
            infixes: "two:three".to_owned(),
            suffix: Number(4),
        }
    );

    Ok(())
}

Structs

Enums

Type Aliases