a better regex for time parsing

automove
Ondřej Hruška 5 years ago
parent 07faba35b9
commit e1eb0c202e
Signed by: MightyPork
GPG Key ID: 2C5FD5035250423D
  1. 28
      src/main.rs

@ -485,7 +485,7 @@ impl TryFrom<&str> for SubInstant {
f32::from_str(m).unwrap() * 60f32 +
f32::from_str(&s).unwrap())))
}
None => Err(failure::err_msg("Error parsing time."))
None => Err(failure::format_err!("Error parsing time: {}", value))
}
}
}
@ -501,27 +501,23 @@ impl TryFrom<&str> for SubDuration {
fn try_from(value: &str) -> Result<Self, Self::Error> {
lazy_static! {
static ref TIME_RE: Regex = Regex::new(r"^(-)?(?:(\d+):)?(?:(\d+):)?(\d+(?:[,.]\d+)?)$").unwrap();
static ref TIME_RE: Regex = Regex::new(r"^(?P<n>-)?(?:(?:(?P<h>\d+):)?(?P<m>\d+):)?(?P<s>\d+(?:[.,]\d+)?)$").unwrap();
}
match TIME_RE.captures(value) {
Some(caps) => {
let minus = if caps.get(1).is_some() { -1f32 } else { 1f32 };
let a = caps.get(2).map(|m| m.as_str()).unwrap_or("");
let b = caps.get(3).map(|m| m.as_str()).unwrap_or("");
let s = caps.get(4).map(|m| m.as_str()).unwrap_or("0").replace(",", ".");
let (h, m) = if b.is_empty() {
("0", if a.is_empty() { "0" } else { a })
} else {
(a, b)
};
let minus = if caps.name("n").is_some() { -1f32 } else { 1f32 };
let h = caps.name("h").map_or(0f32, |m| f32::from_str(m.as_str()).unwrap());
let m = caps.name("m").map_or(0f32, |m| f32::from_str(m.as_str()).unwrap());
let s = caps.name("s").map_or(0f32, |m| f32::from_str(&m.as_str().replace(",", ".")).unwrap());
Ok(SubDuration(minus * (f32::from_str(h).unwrap() * 3600f32 +
f32::from_str(m).unwrap() * 60f32 +
f32::from_str(&s).unwrap())))
Ok(SubDuration(minus * (h * 3600f32 +
m * 60f32 +
s)))
}
None => {
Err(failure::format_err!("Error parsing time: {}", value))
}
None => Err(failure::err_msg("Error parsing time: No match"))
}
}
}

Loading…
Cancel
Save