I needed a more general method to extract a list of integers from a string, so I wrote my own method. I am not sure if this is better than all the above because I have not tested them. There he is:
public static List<Integer> getAllIntegerNumbersAfterKeyFromString(
String text, String key) throws Exception {
text = text.substring(text.indexOf(key) + key.length());
List<Integer> listOfIntegers = new ArrayList<Integer>();
String intNumber = "";
char[] characters = text.toCharArray();
boolean foundAtLeastOneInteger = false;
for (char ch : characters) {
if (Character.isDigit(ch)) {
intNumber += ch;
} else {
if (intNumber != "") {
foundAtLeastOneInteger = true;
listOfIntegers.add(Integer.parseInt(intNumber));
intNumber = "";
}
}
}
if (!foundAtLeastOneInteger)
throw new Exception(
"No matching integer was found in the provided string!");
return listOfIntegers;
}
The @key parameter is optional. It can be deleted if you delete the first line of the method:
text = text.substring(text.indexOf(key) + key.length());
or you can just download it with "".
source
share