简体   繁体   中英

Split using regular expression, but getting first array element as blank space

Kidly help me findout why ac[0] is blank

public class AddtheNumbers {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String abc="bajsd 7 jns 87 5";
        String ac[]=abc.trim().split("\\D+");

        System.out.println(ac[0]);
        System.out.println(ac[1]);
        System.out.println(ac[2]);
      }
}

Because you are splitting on not digits, and the first thing is not a digit. Hence the blank. I would try something like this

import java.util.regex.*;
public class AddtheNumbers {

    public static void main(String[] args) {
       Pattern p = Pattern.compile("-?\\d+");
       Matcher m = p.matcher("bajsd 7 jns 87 5");
       while (m.find()) {
         System.out.println(m.group());
       }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM