tags:

views:

237

answers:

3

Hi! 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?

UPDATE

Thanks for your answers. 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());
}
A: 

for rational numbers use this one: (([0-9]+.[0-9]*)|([0-9]*.[0-9]+)|([0-9]+))

Andrey
The OP said integers, not real numbers. Also, you forgot to escape the dots, and none of those parentheses are necessary.
Alan Moore
+2  A: 
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.

Sean Owen
Could you complement your answer by explaining your regular expression please?
OscarRyz
-? 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 more more digits
Sean Owen
A: 
Pattern p = Pattern.compile("[0-9]+");
Matcher m = p.matcher(myString);
while (m.find()) {
    int n = Integer.parseInt(m.group());
    // append n to list
}
// convert list to array, etc

You can actually replace [0-9] with \d, but that involves double backslash escaping, which makes it harder to read.

sidereal
Whoops. Sean's handles negative numbers, so that's an improvement.
sidereal