Java Data Type How to - Extract multiple integers from a String








Question

We would like to know how to extract multiple integers from a String.

Answer

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/*w w w  .j  a v a 2s .  c o  m*/
public class Main {
    public static void main(String[] args) {
        String s = "(123, 234; 345, 456) (567, 788; 899, 900)";
        Matcher m = Pattern.compile("\\d+").matcher(s);
        List<Integer> numbers = new ArrayList<Integer>();
        while(m.find()) {
            numbers.add(Integer.parseInt(m.group()));
        }
        System.out.println(numbers);
    }
}