Parse multiple doubles from a String

只愿长相守 提交于 2019-12-18 07:05:05

问题


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.


回答1:


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



回答2:


You could search for the following regex:

Pattern.compile("[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?")

and then use Double.parseDouble() on each match.




回答3:


  1. Parse out the substring (surrounded by whitespace)

  2. Use String.ParseDouble() to get the numeric value

Here's one example, using "split()" to parse (there are many alternatives):

// http://pages.cs.wisc.edu/~hasti/cs302/examples/Parsing/parseString.html

String phrase = "the music made   it   hard      to        concentrate";
String delims = "[ ]+";
String[] tokens = phrase.split(delims);

Here's a second alternative:

Java: how to parse double from regex




回答4:


You'll need to think about what sort of algorithm you'd want to use to do this, as it's not entirely obvious. If a substring is asdf.1asdf, should that be parsed as the decimal value 0.1 or simply 1?

Also, can some of the embedded numbers be negative? If not this greatly simplifies the search space.

I think that aix is on the right track with using a regex, since once you come up with an algorithm this sounds like the kind of job for a state machine (scan through the input until you find a digit or optionally a - or ., then look for the next "illegal" character and parse the substring normally).

It's the edge cases that you have to think about though - for example, without negative numbers you can almost use s.split("[^0-9.]") and filter out the non-empty elements. However, period characters that aren't part of a number will get you. Whatever solution you go with, think about whether any situations could trip it up.



来源:https://stackoverflow.com/questions/9381560/parse-multiple-doubles-from-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!