如何从字符串中提取 double 值?
例如,s=“1.2+3.4*(3.2+2.3)-12.1/3.4*1.8+5.7”
如何提取 double 值并将其存储为变量?
最佳答案
您可以通过模式匹配来完成并抓取匹配部分
Pattern p = Pattern.compile("[0-9]*\\.?[0-9]+");
Matcher m = p.matcher("1.2+3.4*(3.2+2.3)-12.1/3.4*1.8+5.7");
while (m.find()) {
System.out.println(m.group());
}
然后您可以将所有匹配的数据收集到 List<Double>
或List<Float>
根据您的要求
要收集运算符,您需要添加另一个模式来查找,请参阅 ORing 部分
([0-9]*\.?[0-9]+)|(\+|-|\/|\(|\|\)|\*)
<小时/>
查看
关于java - 如何从这样的字符串中提取 double ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22571186/