String str = "12 hi when 8 and 9";
str=str.replaceAll("[\\D]+"," "); // returns 12 8 9
String[] numbers=str.split(" ");
int sum = 0;
for(int i=0;i<numbers.length;i++){
sum+=Integer.parseInt(numbers[i]);
}
\\d* matches 0 or more digits, and so it even matches an empty string.
Use \\d+ to match only 1 and more digits
Greedy quantifiers
X? X, once or not at all
X* X, zero or more times
X+ X, one or more times