Java函数解析字符串中的所有双精度数

nlu*_*ira 0 java

我知道之前已经有人问过这个问题\xc2\xb9\xc2\xb9 ,但答复似乎并没有涵盖所有极端情况。

\n

我尝试用测试用例实现建议\xc2\xb9

\n

String("Doubles -1.0, 0, 1, 1.12345 and 2.50")

\n

哪个应该返回

\n

[-1, 0, 1, 1.12345, 2.50]

\n
import java.util.Scanner;\nimport java.util.ArrayList;\nimport java.util.Locale;\npublic class Main\n{\n    public static void main(String[] args) {\n        String string = new String("Doubles -1.0, 0, 1, 1.12345 and 2.50");\n        System.out.println(string);\n        ArrayList<Double> doubles = getDoublesFromString(string);\n        System.out.println(doubles);\n    }\n    \n    public static ArrayList<Double> getDoublesFromString(String string){\n        Scanner parser = new Scanner(string);\n        parser.useLocale(Locale.US);\n        ArrayList<Double> doubles = new ArrayList<Double>();\n        double currentDouble;\n        while (parser.hasNext()){\n            if(parser.hasNextDouble()){\n                currentDouble = parser.nextDouble();\n                doubles.add(currentDouble);\n            }\n            else {\n                parser.next();\n            }\n        }\n        parser.close();\n        return doubles;\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n

相反,上面的代码返回[1.12345, 2.5].

\n

难道是我执行错了?捕获负数和 0 的修复方法是什么?

\n

Tim*_*sen 5

我会在这里使用正则表达式查找所有方法:

String string = new String("Doubles -1.0, 0, 1, 1.12345 and 2.50");
List<String> nums = new ArrayList<>();

String pattern = "-?\\d+(?:\\.\\d+)?";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(string);

while (m.find()) {
    nums.add(m.group());
}

System.out.println(nums);  // [-1.0, 0, 1, 1.12345, 2.50]
Run Code Online (Sandbox Code Playgroud)

顺便说一句,你的问题使用了String构造函数,它很少使用,但很有趣,特别是对于我们这些从不使用它的人来说。

这是正则表达式模式的解释:

-?            match an optional leading negative sign
\\d+          match a whole number
(?:\\.\\d+)?  match an optional decimal component
Run Code Online (Sandbox Code Playgroud)