Can I extract numbers from string without counting the amount of numbers in that string?

Viewed 133

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

2 Answers

You can use the String method split with regex \\D+ like below:

String stringWithNumbers = "1111llalbhahbah2222albhlahbahb3333lHVvlVLH4444ABHABHB";
String[] s = stringWithNumbers.split("\\D+");
System.out.println(Arrays.toString(s)); //it will print [1111, 2222, 3333, 4444]

Try this:

String stringWithNumbers = "1111llalbhahbah2222albhlahbahb3333lHVvlVLH4444ABHABHB";
int[] numbersFromString = Stream.of(stringWithNumbers.split("[a-zA-Z]+")).mapToInt(Integer::parseInt).toArray();

for (int i: numbersFromString)
{
     System.out.println(i);
}

Output:

1111
2222
3333
4444
Related