Skip to content

Conversation

@Canop
Copy link
Owner

@Canop Canop commented Jul 23, 2024

Those two macros allow conditional computation based on regex matching, with variables declared from the named capturing groups.

Of course the regexes are lazy static and checked at compile time.

Example with regex_if!

 let s = "gray(15)";
 let gray = regex_if!(
        r#"^gr(a|e)y\((?<level>\d{1,2})\)$"#,
        s,
        level.parse()?,
 );
 assert_eq!(gray, Some(15));

Example with regex_switch!

#[derive(Debug, PartialEq)]
enum Color {
    Grey(u8),
    Pink,
    Rgb(u8, u8, u8),
}
let input = "rgb(1, 2, 3)";
let color = regex_switch!(input,
    r#"^gr(a|e)y\((?<level>\d{1,2})\)$"#i => {
        Color::Grey(level.parse()?)
    }
    "^pink"i => Color::Pink,
    r#"^rgb\((?<r>\d+),\s*(?<g>\d+),\s*(?<b>\d+),?\)$"#i => Color::Rgb (
        r.parse()?,
        g.parse()?,
        b.parse()?,
    ),
);
assert_eq!(color, Some(Color::Rgb(1, 2, 3)));

@Canop
Copy link
Owner Author

Canop commented Jul 23, 2024

I might add the bytes_ variant. I'd like some feedback before I merge this.

@Canop Canop merged commit d508e24 into main Jul 25, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants