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(m).unwrap() * 60f32 +
f32::from_str(&s).unwrap()))) 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> { fn try_from(value: &str) -> Result<Self, Self::Error> {
lazy_static! { 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) { match TIME_RE.captures(value) {
Some(caps) => { Some(caps) => {
let minus = if caps.get(1).is_some() { -1f32 } else { 1f32 }; let minus = if caps.name("n").is_some() { -1f32 } else { 1f32 };
let a = caps.get(2).map(|m| m.as_str()).unwrap_or(""); let h = caps.name("h").map_or(0f32, |m| f32::from_str(m.as_str()).unwrap());
let b = caps.get(3).map(|m| m.as_str()).unwrap_or(""); let m = caps.name("m").map_or(0f32, |m| f32::from_str(m.as_str()).unwrap());
let s = caps.get(4).map(|m| m.as_str()).unwrap_or("0").replace(",", "."); let s = caps.name("s").map_or(0f32, |m| f32::from_str(&m.as_str().replace(",", ".")).unwrap());
let (h, m) = if b.is_empty() {
("0", if a.is_empty() { "0" } else { a })
} else {
(a, b)
};
Ok(SubDuration(minus * (f32::from_str(h).unwrap() * 3600f32 + Ok(SubDuration(minus * (h * 3600f32 +
f32::from_str(m).unwrap() * 60f32 + m * 60f32 +
f32::from_str(&s).unwrap()))) s)))
}
None => {
Err(failure::format_err!("Error parsing time: {}", value))
} }
None => Err(failure::err_msg("Error parsing time: No match"))
} }
} }
} }

Loading…
Cancel
Save