从字符串中解析多个双精度数

2022-01-17 00:00:00 string numbers parsing double java

我想知道如何从一个字符串中解析几个双数,但是字符串可以混合,例如: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 );
}

相关文章