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 wondering whether there was a quick solution with regular expressions?
I used Sean's solution and changed it slightly:
LinkedList<String> numbers = new LinkedList<String>(); Pattern p = Pattern.compile("\\d+"); Matcher m = p.matcher(line); while (m.find()) { numbers.add(m.group()); }
You can convert a String to integer using the parseInt() method of the Integer class. To convert a string array to an integer array, convert each element of it to integer and populate the integer array with them.
In Java, we can use Integer. valueOf() and Integer. parseInt() to convert a string to an integer.
Pattern p = Pattern.compile("-?\\d+"); Matcher m = p.matcher("There are more than -2 and less than 12 numbers here"); while (m.find()) { System.out.println(m.group()); }
... prints -2
and 12
.
-? matches a leading negative sign -- optionally. \d matches a digit, and we need to write \
as \\
in a Java String though. So, \d+ matches 1 or more digits.
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”If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With