Parse multiple doubles from a String

后端 未结 4 1522
轮回少年
轮回少年 2020-12-20 01:57

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

4条回答
  •  不知归路
    2020-12-20 02:32

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

提交回复
热议问题