从字符串中获取双倍

我有一个字符串包含以下内容:“按照自己的方式,11.95苏格兰历史,14.50,一天学习微积分,29.95”有什么方法可以从这个字符串中获得双打?

使用正则表达式提取双精度数,然后使用Double.parseDouble()解析:

Pattern p = Pattern.compile("(\\d+(?:\\.\\d+))"); Matcher m = p.matcher(str); while(m.find()) { double d = Double.parseDouble(m.group(1)); System.out.println(d); } 

Java提供了Scanner ,它允许您扫描String(或任何输入流)并使用正则表达式解析基本类型和字符串标记。

使用它而不是编写自己的正则表达式可能更适合,纯粹出于维护原因。

 Scanner sc = new Scanner(yourString); double price1 = sc.nextDouble(), price2 = sc.nextDouble(), price3 = sc.nextDouble(); 

如果您对包含数字,单个句点和更多数字的任何和所有数字感兴趣,则需要使用正则表达式。 例如\s\d*.\d\s ,表示空格,后跟数字,句点,更多数字,并以空格结束。

这会找到双精度数,整数(有和没有小数点)和分数(前导小数点):

 public static void main(String[] args) { String str = "This is whole 5, and that is double 11.95, now a fraction .25 and finally another whole 3. with a trailing dot!"; Matcher m = Pattern.compile("(?!=\\d\\.\\d\\.)([\\d.]+)").matcher(str); while (m.find()) { double d = Double.parseDouble(m.group(1)); System.out.println(d); } } 

输出:

 5.0 11.95 0.25 3.0 

使用扫描仪(例如TutorialPoint)。 上面建议的正则表达式在此示例中失败: "Hi! -4 + 3.0 = -1.0 true"检测到{3.0, 1,0}

  String s = ""Hello World! -4 + 3.0 = -1.0 true""; // create a new scanner with the specified String Object Scanner scanner = new Scanner(s); // use US locale to be able to identify doubles in the string scanner.useLocale(Locale.US); // find the next double token and print it // loop for the whole scanner while (scanner.hasNext()) { // if the next is a double, print found and the double if (scanner.hasNextDouble()) { System.out.println("Found :" + scanner.nextDouble()); } // if a double is not found, print "Not Found" and the token System.out.println("Not Found :" + scanner.next()); } // close the scanner scanner.close(); } 
 String text = "Did It Your Way, 11.95 The History of Scotland, 14.50, Learn Calculus in One Day, 29.95"; List foundDoubles = Lists.newLinkedList(); String regularExpressionForDouble = "((\\d)+(\\.(\\d)+)?)"; Matcher matcher = Pattern.compile(regularExpressionForDouble).matcher(text); while (matcher.find()) { String doubleAsString = matcher.group(); Double foundDouble = Double.valueOf(doubleAsString); foundDoubles.add(foundDouble); } System.out.println(foundDoubles); 

当我从用户那里得到输入并且不知道它的外观时,我就是这样做的:

  Vector foundDoubles = new Vector(); Scanner reader = new Scanner(System.in); System.out.println("Ask for input: "); for(int i = 0; i < accounts.size(); i++){ foundDoubles.add(reader.nextDouble()); } 

使用您喜欢的语言的正则表达式(正则表达式[p])模块,为模式构建匹配器\d+\.\d+ ,将匹配器应用于输入字符串,并将匹配的子字符串作为捕获组。