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");
find method which will return all matching substrings. You can do it like
Pattern reg = Pattern.compile("\\d+"); Matcher m = reg.matcher("asd0085 sa223 9349x"); while (m.find()) System.out.println(m.group());
which will print
0085 223 9349
Based on your regex it seems that your goal is also to remove leading zeroes like in case of
0085. If that is true, you can use regex like
0*(\\d+) and take part matched by group 1 (the one in parenthesis) and let leading zeroes be matched outside of that group.
Pattern reg = Pattern.compile("0*(\\d+)"); Matcher m = reg.matcher("asd0085 sa223 9349x"); while (m.find()) System.out.println(m.group(1));
85 223 9349
But if you really want to use
split then change
\\D+0* so you could split on one-or-more non-digits
\\D+, not just one non-digit
\\D, but with this solution you may need to ignore first empty element in result array (depending if string will start with element which should be split on, or not).