Reputation: 177
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.
Upvotes: 2
Views: 4671
Reputation: 103847
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.
Upvotes: 0
Reputation: 25950
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 );
}
Upvotes: 3
Reputation: 121881
Parse out the substring (surrounded by whitespace)
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
Upvotes: 1
Reputation: 500913
You could search for the following regex:
Pattern.compile("[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?")
and then use Double.parseDouble()
on each match.
Upvotes: 7