【问题标题】:Parse a number of a certain size in nom解析 nom 中一定大小的一个数
【发布时间】:2020-12-05 10:54:29
【问题描述】:

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

map_res(digit1, |s: &str| s.parse::<u16>())

但是如何才能解析一个只有在一定范围内的数字呢?

【问题讨论】:

    标签: rust nom


    【解决方案1】:

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

    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())),
        }
    })
    

    匹配也可以用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)
                }
            })
    })
    

    【讨论】:

    • 好的。但是这两个都不是 nom 的一部分,对吧?
    • @Alper Right,虽然 nom 可能 包含执行类似操作的实用函数 - 我没有检查。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 2017-08-05
    • 2019-03-14
    • 2021-05-04
    • 1970-01-01
    • 2017-10-08
    • 1970-01-01
    相关资源
    最近更新 更多