解析以任何字符分隔的数字字符串

解析以任何字符分隔的数字字符串

 

    public static void main(String[] args) throws Exception {
        String numStr = "1fda2321fdf,1231 214 \n 345n234 23423saf23";
        List<Integer> list = parseNum2List(numStr);
        System.out.println(list);
    }

    private static List<Integer> parseNum2List(String numStr) {
        List<Integer> list = new ArrayList<Integer>();
        StringBuilder sb = null;
        int len = numStr.length();
        for (int i = 0;i < len;i++) {
            char ch = numStr.charAt(i);
            if (Character.isDigit(ch)) {
                if(null == sb){
                    sb = new StringBuilder();
                }
                sb.append(ch);
            } else {
                if (null != sb) {
                    list.add(StringUtil.toInt(sb.toString()));
                    sb = null;
                }
            }
        }
        // Add the last num.
        if (null != sb) {
            list.add(StringUtil.toInt(sb.toString()));
        }
        return list;
    }

 

输出:

[1, 2321, 1231, 214, 345, 234, 23423, 23]

 

你可能感兴趣的:(字符串)