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));
If you don't have negative numbers, you can get rid of replaceAll (and use !s.isEmpty() in the filter ), since this is only for properly splitting something like 2-34 (this can also be handled purely with a regular expression in split , but it's pretty complicated).
Arrays.stream turns our String[] into a Stream<String> .
filter eliminates leading and trailing empty lines, as well as any - which are not part of the number.
mapToInt(Integer::parseInt).toArray() calls parseInt for each String to give us int[] .
Alternatively, in Java 9 there is a Matcher.results method, which should provide 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));
None of them are currently a big improvement over simple cyclic display of results using Pattern / Matcher as shown in other answers, but this should be simpler if you want to perform more complex operations that are greatly simplified by using threads .
Dukeling Dec 31 '17 at 14:33 2017-12-31 14:33
source share