i have a string containing the following: "Did It Your Way, 11.95 The History of Scotland, 14.50, Learn Calculus in One Day, 29.95" is there any way to get the doubles from this string?
This finds doubles, whole numbers (with and without a decimal point), and fractions (a leading decimal point):
public static void main(String[] args)
{
String str = "This is whole 5, and that is double 11.95, now a fraction .25 and finally another whole 3. with a trailing dot!";
Matcher m = Pattern.compile("(?!=\\d\\.\\d\\.)([\\d.]+)").matcher(str);
while (m.find())
{
double d = Double.parseDouble(m.group(1));
System.out.println(d);
}
}
Output:
5.0
11.95
0.25
3.0
Use regular expressions to extract doubles, then Double.parseDouble() to parse:
Pattern p = Pattern.compile("(\\d+(?:\\.\\d+))");
Matcher m = p.matcher(str);
while(m.find()) {
double d = Double.parseDouble(m.group(1));
System.out.println(d);
}
Java provides Scanner which allows you to scan a String (or any input stream) and parse primitive types and string tokens using regular expressions.
It would likely be preferrable to use this rather than writing your own regex, purely for maintenance reasons.
Scanner sc = new Scanner(yourString);
double price1 = sc.nextDouble(),
price2 = sc.nextDouble(),
price3 = sc.nextDouble();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With