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
)
);
最佳答案
您还需要用tag!(".")
包装complete!
,如下所示:
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
)
);
如果输入是
123
,则tag!
将返回Incomplete
,因为它无法确定下一个输入是否是.
关于rust - 使用Nom将整数解析为浮点型,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42790494/