Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove empty results after splitting with regex in Java?

Tags:

java

regex

I want to find all numbers from a given string (all numbers are mixed with letters but are separated by space).I try to split the input String but when check the result array I find that there are a lot of empty Strings, so how to change my split regex to remove this empty spaces?

Pattern reg = Pattern.compile("\\D0*");
String[] numbers = reg.split("asd0085 sa223 9349x");
for(String s:numbers){
    System.out.println(s);
}

And the result:

85


223
9349

I know that I can iterate over the array and to remove empty results. But how to do it only with regex?

like image 989
Xelian Avatar asked Aug 22 '14 16:08

Xelian


1 Answers

If you are using java 8, you can do it in 1 statement like this:

String[] array = Arrays.asList(s1.split("[,]")).stream().filter(str -> !str.isEmpty()).collect(Collectors.toList()).toArray(new String[0]);
like image 121
Akın Özer Avatar answered Oct 20 '22 06:10

Akın Özer