rust - 使用 Nom 将整数解析为 float

标签 rust nom

Nom 有一个 example of parsing a floating point number :

named!(unsigned_float <f32>, map_res!(
  map_res!(
    recognize!(
      alt!(
        delimited!(digit, tag!("."), opt!(complete!(digit))) |
        delimited!(opt!(digit), tag!("."), digit)
      )
    ),
    str::from_utf8
  ),
  FromStr::from_str
));

我想扩展此示例,使其也支持将 "123" 解析为 123.0。我试过这样的事情但没有运气:

named!(unsigned_float_v1 <f32>,
    map_res!(
        map_res!(
            alt!(
                recognize!(
                    alt!(
                        delimited!(digit, tag!("."), opt!(complete!(digit))) |
                        delimited!(opt!(digit), tag!("."), digit)
                    )
                ) |
                ws!(digit)
            ),
            str::from_utf8
        ),
        FromStr::from_str
    )
);

named!(unsigned_float_v2 <f32>,
    map_res!(
        map_res!(
            recognize!(
                alt!(
                    delimited!(digit, tag!("."), opt!(complete!(digit))) |
                    delimited!(opt!(digit), tag!("."), digit) |
                    digit
                )
            ),
            str::from_utf8
        ),
        FromStr::from_str
    )
);

最佳答案

你还需要用complete!包裹tag!("."),如下:

named!(unsigned_float_v2 <f32>,
    map_res!(
        map_res!(
            recognize!(
                alt!(
                    delimited!(digit, complete!(tag!(".")), opt!(complete!(digit))) |
                    delimited!(opt!(digit), complete!(tag!("."), digit) |
                    digit
                )
            ),
            str::from_utf8
        ),
        FromStr::from_str
    )
);

如果输入是 123tag! 将返回 Incomplete,因为它无法确定下一个输入是否是

关于rust - 使用 Nom 将整数解析为 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42790494/

相关文章:

http - 为什么来自 api.color.pizza 的 reqwest 响应会返回意外的字节?

rust - 特质界限是否应该在struct和impl中重复?

types - 使用 nom 解析字面量和返回值

rust 标称 : many and end of input

rust - 使用 Hyper 的 Rust 客户端证书

rust - 如何在 `tokio` 中获得与sync_channel(0) 等效的值?

rust - 使用生命周期参数声明特征对象的向量

rust - 如何使用 nom 将 u128 整数转换为 Uuid

rust - 使用 nom 5.0 解析数字

parsing - 如何使用 nom 精确匹配一个字节?