I have a String variable (basically an English sentence with an unspecified number of numbers) and I\'d like to extract all the numbers into an array of integers. I was wond
What about to use replaceAll
java.lang.String method:
String str = "qwerty-1qwerty-2 455 f0gfg 4";
str = str.replaceAll("[^-?0-9]+", " ");
System.out.println(Arrays.asList(str.trim().split(" ")));
Output:
[-1, -2, 455, 0, 4]
Description
[^-?0-9]+
[
and ]
delimites a set of characters to be single matched, i.e., only one time in any order^
Special identifier used in the beginning of the set, used to indicate to match all characters not present in the delimited set, instead of all characters present in the set.+
Between one and unlimited times, as many times as possible, giving back as needed-?
One of the characters “-” and “?”0-9
A character in the range between “0” and “9”