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

前端 未结 7 1700
臣服心动
臣服心动 2021-01-17 16:02

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 arra

7条回答
  •  醉酒成梦
    2021-01-17 16:27

    Using String.split(), you get an empty string as array element, when you have back to back delimiter in your string, on which you're splitting.

    For e.g, if you split xyyz on y, the 2nd element will be an empty string. To avoid that, you can just add a quantifier to delimiter - y+, so that split happens on 1 or more iteration.

    In your case it happens because you've used \\D0* which will match each non-digit character, and split on that. Thus you've back to back delimiter. You can of course use surrounding quantifier here:

    Pattern reg = Pattern.compile("(\\D0*)+");   
    

    But what you really need is: \\D+0* there.

    However, if what you only want is the numeric sequence from your string, I would use Matcher#find() method instead, with \\d+ as regex.

提交回复
热议问题