如何在不进行手动解析的情况下从可能包含剩余字符的字符串中解析浮点数? [英] How do I parse a float from a string that might contain left-over characters without doing manual parsing?
问题描述
我如何从可能包含剩余字符的字符串中解析浮点数,并找出其结尾,而无需进行手动解析(例如JS中的 parseFloat()
)?
How do I parse a float from a string that may contain left-over characters, and figure out where it ends, without doing manual parsing (e.g. parseFloat()
in JS)?
一个例子是字符串"2e-1!"
.我想评估字符串中的下一个浮点数,以便可以将此字符串拆分为"2e-1"
和!"
>(例如,如果我想实现一个计算器.)如何在不编写解析器的情况下 来查看浮点数的结尾,并将其作为& str
,然后使用 .parse()
?
An example would be the string "2e-1!"
. I want to evaluate the next float from the string such that I can split this string into "2e-1"
and "!"
(for example, if I wanted to implement a calculator.) How would I do this without writing a parser to see where the float ends, taking that as an &str
, and then using .parse()
?
我知道这意味着我可能必须将非标准内容(例如"3e + 1 + e3"
解析为 3e + 1
( 30
)和"+ e3"
.这是有意的;我不知道格式化浮点数的所有方法,特别是对Rust的 parse ::< f64>()
有效的方法,但是我想不管如何处理它们.
I am aware that this means that I may have to parse nonstandard things such as "3e+1+e3"
to 3e+1
(30
) and "+e3"
. This is intended; I do not know all of the ways to format floating point numbers, especially the ones valid to Rust's parse::<f64>()
, but I want to handle them regardless.
我该如何做?最好不要使用外部库?
How can I do this, preferably without external libraries?
推荐答案
如注释中所述,您需要实现自己的浮点解析器或使用外部库.标准库中的解析器遇到它时总是出错输入字符串中有多余的垃圾 –甚至不允许前导或尾随空格.
As mentioned in the comments, you need to either implement your own floating-point parser or use an external library. The parser in the standard library always errors out when it encounters additional junk in the input string – it doesn't even allow leading or trailing whitespace.
要使用的外部包装箱最好是 nom
.它带有浮点数集成解析器符合您的要求.例子:
A good external crate to use is nom
. It comes with an integrated parser for floating-point numbers that meets your requirements. Examples:
use nom::number::complete::double;
let parser = double::<_, ()>;
assert_eq!(parser("2.0 abc"), Ok((" abc", 2.0)));
let result = parser("Nanananananana hey, Jude!").unwrap();
assert_eq!(result.0, "ananananana hey, Jude!");
assert!(result.1.is_nan());
解析器期望在字符串的最开始处有浮点数.如果要允许前导空格,则可以先使用 trim_start()
删除它.
The parser expects the floating-point number at the very beginning of the string. If you want to allow leading whitespace, you can remove it first using trim_start()
.
这篇关于如何在不进行手动解析的情况下从可能包含剩余字符的字符串中解析浮点数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!