从字符串中解析多个双精度数
我想知道如何从字符串中解析多个双精度数字,但字符串可以混合,例如:String s = "text 3.454 sometext5.567568more_text"
。
标准方法(Double.parseDouble
)不合适。我尝试使用 isDigit 方法解析它,但是如何解析其他字符和 .
?
谢谢。
I would like to know how to parse several double numbers from a string, but string can be mixed, for instance: String s = "text 3.454 sometext5.567568more_text"
.
The standard method (Double.parseDouble
) is unsuitable. I've tried to parse it using the isDigit
method, but how to parse other characters and .
?
thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以搜索 以下正则表达式:
然后使用
Double.parseDouble()
每场比赛。You could search for the following regex:
and then use
Double.parseDouble()
on each match.使用合适的正则表达式(如此代码或其他帖子中所示)解析双精度数后,迭代将匹配的双精度数添加到列表中。在这里,您已经可以在代码中的其他任何地方使用
myDoubles
了。After parsing your doubles with the suitable regular expressions like in this code or in other posts, iterate to add the matching ones to a list. Here you have
myDoubles
ready to use anywhere else in your code.解析出子字符串(被空格包围)
使用 String.ParseDouble() 获取数值
这是一个例子,使用“split()”来解析(有很多替代方案):
这是第二种替代方案:
Java:如何从正则表达式解析双精度
Parse out the substring (surrounded by whitespace)
Use String.ParseDouble() to get the numeric value
Here's one example, using "split()" to parse (there are many alternatives):
Here's a second alternative:
Java: how to parse double from regex
您需要考虑您想要使用哪种算法来执行此操作,因为它并不完全明显。如果子字符串是
asdf.1asdf
,是否应该将其解析为十进制值0.1
还是简单地1
?另外,某些嵌入的数字可以是负数吗?如果不是,这将大大简化搜索空间。
我认为 aix 使用正则表达式走在正确的轨道上,因为一旦你想出了一个算法,这听起来就像状态机的工作(扫描输入直到找到一个数字)或可选的
-
或.
,然后查找下一个“非法”字符并正常解析子字符串)。不过,您必须考虑边缘情况 - 例如,如果没有负数,您几乎可以使用
s.split("[^0-9.]")
并过滤掉非空元素。但是,不属于数字的句点字符也会让您出错。无论您采用何种解决方案,请考虑是否有任何情况可能会出错。You'll need to think about what sort of algorithm you'd want to use to do this, as it's not entirely obvious. If a substring is
asdf.1asdf
, should that be parsed as the decimal value0.1
or simply1
?Also, can some of the embedded numbers be negative? If not this greatly simplifies the search space.
I think that aix is on the right track with using a regex, since once you come up with an algorithm this sounds like the kind of job for a state machine (scan through the input until you find a digit or optionally a
-
or.
, then look for the next "illegal" character and parse the substring normally).It's the edge cases that you have to think about though - for example, without negative numbers you can almost use
s.split("[^0-9.]")
and filter out the non-empty elements. However, period characters that aren't part of a number will get you. Whatever solution you go with, think about whether any situations could trip it up.