从String解析多个双打 [英] Parse multiple doubles from a String

查看:136
本文介绍了从String解析多个双打的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何从字符串中解析几个双数字,但字符串可以混合,例如: String s =text 3.454 sometext5.567568more_text



标准方法( Double.parseDouble )不适用。我试图使用 isDigit 方法解析它,但是如何解析其他字符和



谢谢。

解决方案

使用适当的正则表达式解析您的双打,该代码或在其他帖子中,迭代将匹配的添加到列表。在这里,您有 myDoubles 准备使用您代码中的其他任何地方。

  public static void main(String args [])
{
String input =text 3.454 sometext5.567568more_text;
ArrayList<双倍> myDoubles = new ArrayList< Double>();
Matcher matcher = Pattern.compile([ - +]?\\d * \\。?\\d +([eE] [ - +]?\\d +)? ).matcher(input);

while(matcher.find())
{
double element = Double.parseDouble(matcher.group());
myDoubles.add(element);
}

(双元素:myDoubles)
System.out.println(element);
}


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.

解决方案

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.

public static void main ( String args[] )
{
    String input = "text 3.454 sometext5.567568more_text";
    ArrayList < Double > myDoubles = new ArrayList < Double >();
    Matcher matcher = Pattern.compile( "[-+]?\\d*\\.?\\d+([eE][-+]?\\d+)?" ).matcher( input );

    while ( matcher.find() )
    {
        double element = Double.parseDouble( matcher.group() );
        myDoubles.add( element );
    }

    for ( double element: myDoubles )
        System.out.println( element );
}

这篇关于从String解析多个双打的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆