From efc9896da7901421b4e687d377e0cb75e2e99c2a Mon Sep 17 00:00:00 2001 From: Jesse Luehrs Date: Tue, 21 Dec 2021 18:58:55 -0500 Subject: slight improvement for regex matching --- src/2020/2/mod.rs | 4 ++-- src/2020/7/mod.rs | 12 ++++-------- src/2020/8/mod.rs | 4 ++-- 3 files changed, 8 insertions(+), 12 deletions(-) (limited to 'src/2020') diff --git a/src/2020/2/mod.rs b/src/2020/2/mod.rs index 75cc4f1..a2ff9df 100644 --- a/src/2020/2/mod.rs +++ b/src/2020/2/mod.rs @@ -9,9 +9,9 @@ pub struct Line { impl Line { fn parse(line: &str) -> Result { - let rx = Regex::new(r"^([0-9]+)-([0-9]+) (.): (.*)$").unwrap(); let captures = - rx.captures(line).context("line failed to match regex")?; + regex_captures!(r"^([0-9]+)-([0-9]+) (.): (.*)$", line) + .context("line failed to match regex")?; let c = captures .get(3) .unwrap() diff --git a/src/2020/7/mod.rs b/src/2020/7/mod.rs index 6199ad0..2c8a1a7 100644 --- a/src/2020/7/mod.rs +++ b/src/2020/7/mod.rs @@ -28,11 +28,7 @@ pub fn part2(graph: Graph) -> Result { } fn parse_line(line: &str) -> Result<(String, Vec<(i64, String)>)> { - let main_rx = Regex::new(r"^(.*) bags contain (.*)\.$").unwrap(); - let contents_rx = Regex::new(r"^([0-9]+) (.*) bags?").unwrap(); - - let captures = main_rx - .captures(line) + let captures = regex_captures!(r"^(.*) bags contain (.*)\.$", line) .context("line failed to match regex")?; let color = captures.get(1).unwrap().as_str(); let contents = captures.get(2).unwrap().as_str(); @@ -44,9 +40,9 @@ fn parse_line(line: &str) -> Result<(String, Vec<(i64, String)>)> { contents .split(", ") .map(|s| { - let captures = contents_rx - .captures(s) - .context("line failed to match regex")?; + let captures = + regex_captures!(r"^([0-9]+) (.*) bags?", s) + .context("line failed to match regex")?; Ok(( captures .get(1) diff --git a/src/2020/8/mod.rs b/src/2020/8/mod.rs index d1908cd..af08f5c 100644 --- a/src/2020/8/mod.rs +++ b/src/2020/8/mod.rs @@ -30,8 +30,8 @@ impl std::str::FromStr for Op { type Err = Error; fn from_str(s: &str) -> std::result::Result { - let rx = Regex::new(r"^([^ ]*) ((?:-|\+)[0-9]+)$").unwrap(); - let captures = rx.captures(s).context("failed to parse line")?; + let captures = regex_captures!(r"^([^ ]*) ((?:-|\+)[0-9]+)$", s) + .context("failed to parse line")?; let ty = captures.get(1).unwrap().as_str().parse()?; let arg = captures .get(2) -- cgit v1.2.3-54-g00ecf