解析 nom 中一定大小的数字

Alp*_*per 3 rust nom

我可以很好地解析这样的数字:

map_res(digit1, |s: &str| s.parse::<u16>())
Run Code Online (Sandbox Code Playgroud)

但是如何仅解析某个范围内的数字呢?

use*_*342 5

您可以检查解析的数字是否符合范围,如果不符合则返回错误:

map_res(digit1, |s: &str| {
    // uses std::io::Error for brevity, you'd define your own error
    match s.parse::<u16>() {
        Ok(n) if n < MIN || n > MAX => Err(io::Error::new(io::ErrorKind::Other, "out of range")),
        Ok(n) => Ok(n),
        Err(e) => Err(io::Error::new(io::ErrorKind::Other, e.to_string())),
    }
})
Run Code Online (Sandbox Code Playgroud)

匹配也可以用and_thenmap_err组合符来表示:

map_res(digit1, |s: &str| {
    s.parse::<u16>()
        .map_err(|e| io::Error::new(io::ErrorKind::Other, e.to_string()))
        .and_then(|n| {
            if n < MIN || n > MAX {
                Err(io::Error::new(io::ErrorKind::Other, "out of range"))
            } else {
                Ok(n)
            }
        })
})
Run Code Online (Sandbox Code Playgroud)