从字符串中获取双倍

时间:2011-07-18 14:31:11

标签: java

我有一个包含以下内容的字符串: “按你的方式行事,11.95苏格兰历史,14.50,一天学习微积分,29.95” 有没有办法从这个字符串中获取双打?

8 个答案:

答案 0 :(得分:13)

使用正则表达式提取双精度数,然后使用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);
}

答案 1 :(得分:8)

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

最好使用它而不是编写自己的正则表达式,纯粹出于维护原因。

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

答案 2 :(得分:1)

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

答案 3 :(得分:1)

这会找到双打,整数(有和没有小数点)和分数(一个小数点前导):

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

答案 4 :(得分:1)

使用扫描仪(来自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();
   }

答案 5 :(得分:0)

String text = "Did It Your Way, 11.95 The History of Scotland, 14.50, Learn Calculus in One Day, 29.95";

List<Double> 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);

答案 6 :(得分:0)

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

    Vector<Double> foundDoubles = new Vector<Double>();

    Scanner reader = new Scanner(System.in);
    System.out.println("Ask for input: ");

    for(int i = 0; i < accounts.size(); i++){
        foundDoubles.add(reader.nextDouble());
    }

答案 7 :(得分:-2)

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