get_year/
lib.rs

1extern crate regex;
2
3use regex::Regex;
4
5/// Get the year from a YYYY-MM-DD Formatted Data
6///
7/// ```rust
8/// # extern crate get_year;
9/// # use get_year::get_year;
10/// assert_eq!("2010".to_string(), get_year("2010-03-14".to_string()))
11/// ```
12pub fn get_year(date: String) -> String {
13    let re = Regex::new(r"(?x)
14(?P<year>\d{4})  # the year
15-
16(?P<month>\d{2}) # the month
17-
18(?P<day>\d{2})   # the day
19").unwrap();
20    let caps = re.captures(date.as_str()).unwrap();
21
22    String::from(&caps["year"])
23}
24
25#[cfg(test)]
26mod tests {
27    use super::*;
28
29    #[test]
30    fn gets_2010() {
31        assert_eq!("2010".to_string(), get_year("2010-03-14".to_string()))
32    }
33    #[test]
34    fn gets_1981() {
35        assert_eq!("1981".to_string(), get_year("1981-13-12".to_string()))
36    }
37}