How to pick up only integer data from an ArrayList of String

前端 未结 4 1600
青春惊慌失措
青春惊慌失措 2021-01-29 11:48

I read a text file and put the data into an ArrayList of String.

The data is like

China 12351235123 Korea 123532523 USA 1234123         


        
4条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-29 12:26

    You can use regex and would be careful that not all that numbers can be in a integer range... so there for the list of longs in the code below

    Example:

    public static void main(String[] args) {
        List longList = new ArrayList();
        Pattern pattern = Pattern.compile("\\w+([0-9]+)");// regex pattern
        for (String string : listOfCountriesAndNumbers) {
            Matcher matcher = pattern.matcher(string);
            for (int i = 0; i < matcher.groupCount(); i++) {
                matcher.find();
                longList.add(Long.parseLong(matcher.group()));
            }
        }
        System.out.println(longList);
    }
    

提交回复
热议问题