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());
}
The accepted answer detects digits but does not detect formated numbers, e.g. 2,000, nor decimals, e.g. 4.8. For such use
-?\\d+(,\\d+)*?\\.?\\d+?
:Output:
[4.8, 2,000]
Fraction and grouping characters for representing real numbers may differ between languages. The same real number could be written in very different ways depending on the language.
The number two million in German
2,000,000.00
and in English
2.000.000,00
A method to fully extract real numbers from a given string in a language agnostic way:
for rational numbers use this one:
(([0-9]+.[0-9]*)|([0-9]*.[0-9]+)|([0-9]+))
I found this expression simplest
I would suggest to check the ASCII values to extract numbers from a String Suppose you have an input String as myname12345 and if you want to just extract the numbers 12345 you can do so by first converting the string to Character Array then use the following psuedocode
once the numbers are extracted append them to an array
Hope this helps