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 fro
Use Regular Expressions (regex[p]) module of your favourite language, construct a Matcher for the pattern \d+\.\d+
, apply the matcher for the input string and you get the matching substrings as capture groups.
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 scanner (example from TutorialPoint).
Regex expressions suggested above fail on this example: "Hi! -4 + 3.0 = -1.0 true"
detects {3.0, 1,0}
.
String s = ""Hello World! -4 + 3.0 = -1.0 true"";
// create a new scanner with the specified String Object
Scanner scanner = new Scanner(s);
// use US locale to be able to identify doubles in the string
scanner.useLocale(Locale.US);
// find the next double token and print it
// loop for the whole scanner
while (scanner.hasNext()) {
// if the next is a double, print found and the double
if (scanner.hasNextDouble()) {
System.out.println("Found :" + scanner.nextDouble());
}
// if a double is not found, print "Not Found" and the token
System.out.println("Not Found :" + scanner.next());
}
// close the scanner
scanner.close();
}
String text = "Did It Your Way, 11.95 The History of Scotland, 14.50, Learn Calculus in One Day, 29.95";
List<Double> foundDoubles = Lists.newLinkedList();
String regularExpressionForDouble = "((\\d)+(\\.(\\d)+)?)";
Matcher matcher = Pattern.compile(regularExpressionForDouble).matcher(text);
while (matcher.find()) {
String doubleAsString = matcher.group();
Double foundDouble = Double.valueOf(doubleAsString);
foundDoubles.add(foundDouble);
}
System.out.println(foundDoubles);
Here is how I did it when I was getting input from a user and didn't know what it would look like:
Vector<Double> foundDoubles = new Vector<Double>();
Scanner reader = new Scanner(System.in);
System.out.println("Ask for input: ");
for(int i = 0; i < accounts.size(); i++){
foundDoubles.add(reader.nextDouble());
}
If you're interested in any and all numbers with digits, a single period, and more digits, you want to use regular expressions. Such as \s\d*.\d\s
, indicating a space, followed by digits, a period, more digits, and finished off with a space.