从字符串中解析多个双精度数 [英] Parse multiple doubles from a String

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

问题描述

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

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".

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

The standard method (Double.parseDouble) is unsuitable. I've tried to parse it using the isDigit method, but how to parse other characters and .?

谢谢.

推荐答案

在使用此代码或其他帖子中的合适正则表达式解析双打后,迭代以将匹配的双打添加到列表中.在这里,您可以在代码中的其他任何地方使用 myDoubles.

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 );
}

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

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