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

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

    Using Java 8, you can do:

    String str = "There 0 are 1 some -2-34 -numbers 567 here 890 .";
    int[] ints = Arrays.stream(str.replaceAll("-", " -").split("[^-\\d]+"))
                     .filter(s -> !s.matches("-?"))
                     .mapToInt(Integer::parseInt).toArray();
    System.out.println(Arrays.toString(ints)); // prints [0, 1, -2, -34, 567, 890]
    

    If you don't have negative numbers, you can get rid of the replaceAll (and use !s.isEmpty() in filter), as that's only to properly split something like 2-34 (this can also be handled purely with regex in split, but it's fairly complicated).

    Arrays.stream turns our String[] into a Stream.

    filter gets rid of the leading and trailing empty strings as well as any - that isn't part of a number.

    mapToInt(Integer::parseInt).toArray() calls parseInt on each String to give us an int[].


    Alternatively, Java 9 has a Matcher.results method, which should allow for something like:

    Pattern p = Pattern.compile("-?\\d+");
    Matcher m = p.matcher("There 0 are 1 some -2-34 -numbers 567 here 890 .");
    int[] ints = m.results().map(MatchResults::group).mapToInt(Integer::parseInt).toArray();
    System.out.println(Arrays.toString(ints)); // prints [0, 1, -2, -34, 567, 890]
    

    As it stands, neither of these is a big improvement over just looping over the results with Pattern / Matcher as shown in the other answers, but it should be simpler if you want to follow this up with more complex operations which are significantly simplified with the use of streams.

提交回复
热议问题