Reputation: 161
Supposedly I have a string that contains: hello 14:12
.
Now I want to extract only the number and have two separate value in two variable like this: first_num value should be int i.e. first_num = 14 and the second variable should store the number after the colon (:
) i.e. second_num = 12.
Upvotes: 1
Views: 8539
Reputation: 565
You can use Regex to solve the problem
public static List<Integer> extractNumbers(String s){
List<Integer> numbers = new ArrayList<Integer>();
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(s);
while(m.find()){
numbers.add(Integer.parseInt(m.group()));
}
return numbers;
}
Upvotes: 2
Reputation: 1154
ReplaceAll is the best solution
String str = "hello 14:12";
str = str.replaceAll("[^0-9]+", " ");
System.out.println(Arrays.asList(str.trim().split(" ")));
In this way you can attain only numbers in the array.
Upvotes: 2