Search code examples
javaarraysregexstringextract

Extracting integers from a String into an Array


I need to extract integers from a String into an array.

I've already got the integers, but I wasn't able to place them into an array.

public static void main(String[] args) {
    String line = "First number 10, Second number 25, Third number 123";
    String numbersLine = line.replaceAll("[^0-9]+", "");
    int result = Integer.parseInt(numbersLine);

    // What I want to get:
    // array[0] = 10;
    // array[1] = 25;
    // array[2] = 123;
}

Solution

  • You can use a regular expression to extract numbers:

    String s = "First number 10, Second number 25, Third number 123 ";
    Matcher matcher = Pattern.compile("\\d+").matcher(s);
    
    List<Integer> numbers = new ArrayList<>();
    while (matcher.find()) {
        numbers.add(Integer.valueOf(matcher.group()));
    }
    

    \d+ stands for any digit repeated one or more times.

    If you loop over the output, you will get:

    numbers.forEach(System.out::println);
    
    // 10
    // 25
    // 123
    

    Note: This solution does only work for Integer, but that is also your requirement.