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

后端 未结 13 819
孤城傲影
孤城傲影 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:20

    If you want to exclude numbers that are contained within words, such as bar1 or aa1bb, then add word boundaries \b to any of the regex based answers. For example:

    Pattern p = Pattern.compile("\\b-?\\d+\\b");
    Matcher m = p.matcher("9There 9are more9 th9an -2 and less than 12 numbers here9");
    while (m.find()) {
      System.out.println(m.group());
    }
    

    displays:

    2
    12
    
    0 讨论(0)
提交回复
热议问题