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

前端 未结 7 1661
臣服心动
臣服心动 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:17

    Don't use split. Use 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));
    

    Output:

    85
    223
    9349
    

    But if you really want to use split then change "\\D0*" to \\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).

提交回复
热议问题