How to extract numbers from a string and get an array of ints?

后端 未结 13 1028
孤城傲影
孤城傲影 2020-11-22 05:32

I have a String variable (basically an English sentence with an unspecified number of numbers) and I\'d like to extract all the numbers into an array of integers. I was wond

13条回答
  •  滥情空心
    2020-11-22 06:11

    Pattern p = Pattern.compile("[0-9]+");
    Matcher m = p.matcher(myString);
    while (m.find()) {
        int n = Integer.parseInt(m.group());
        // append n to list
    }
    // convert list to array, etc
    

    You can actually replace [0-9] with \d, but that involves double backslash escaping, which makes it harder to read.

提交回复
热议问题