Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract numbers from a string and get an array of ints?

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()); } 
like image 412
John Manak Avatar asked Mar 02 '10 22:03

John Manak


People also ask

How do you convert a string of numbers to an array of numbers?

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.

How do you extract an int from a string?

In Java, we can use Integer. valueOf() and Integer. parseInt() to convert a string to an integer.


2 Answers

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.

like image 117
Sean Owen Avatar answered Sep 21 '22 08:09

Sean Owen


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”
like image 22
Maxim Shoustin Avatar answered Sep 20 '22 08:09

Maxim Shoustin