I need to extract numbers from string to an array of int, but I could not find appropriate function in Matcher class. Is there any way to do this better way than I? For example such split() function split string by delimiter and return prepared array.
import java.util.regex.*;
public class Test
{
public static void main(String[] args)
{
String stringWithNumbers = "1111llalbhahbah2222albhlahbahb3333lHVvlVLH4444ABHABHB";
int[] numbersFromString;
// find amount of numbers in stringWithNumbers
Pattern toFindNumbers = Pattern.compile("\\d+");
Matcher m1 = toFindNumbers.matcher(stringWithNumbers);
int amountOfNumbers = 0;
while (m1.find()) amountOfNumbers++;
// fill array with numbers
numbersFromString = new int[amountOfNumbers];
m1.reset();
for (int i = 0; m1.find(); i++)
{
numbersFromString[i] = Integer.parseInt(m1.group());
}
// print array (test)
for (int i: numbersFromString)
{
System.out.println(i);
}
}
}
Output:
1111
2222
3333
4444