Skip to content

Instantly share code, notes, and snippets.

@bongole
Created February 16, 2017 10:16
Show Gist options
  • Save bongole/ada5d6fa1d77c175909f2d144ce85c7b to your computer and use it in GitHub Desktop.
Save bongole/ada5d6fa1d77c175909f2d144ce85c7b to your computer and use it in GitHub Desktop.
nomで日付のパーステスト
#[macro_use]
extern crate nom;
use nom::*;
fn take_digits_n(input: &[u8], n: u8) -> IResult<&[u8],&[u8]> {
verify!(input, take!(n), |chars: &[u8]| chars.iter().all(|c: &u8| is_digit(*c)) )
}
named!(take_4_digits, apply!(take_digits_n, 4));
named!(take_1_or_2_digits, alt_complete!( apply!(take_digits_n, 2) | apply!(take_digits_n, 1)) );
named!(date<(&str, &str, &str)>, do_parse!(
year: map_res!(take_4_digits, std::str::from_utf8) >>
tag!("-") >>
month: map_res!(take_1_or_2_digits, std::str::from_utf8) >>
tag!("-") >>
day: map_res!(take_1_or_2_digits, std::str::from_utf8) >>
(year, month, day)
)
);
fn main() {
println!("{:?}", date(b"2017-1-30"));
println!("{:?}", date(b"2017-1-1"));
println!("{:?}", date(b"2017-10-30"));
println!("{:?}", date(b"2017-100-300")); // parse error
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment