简体   繁体   中英

JAVA split with regex doesn't work

I have the following String 46MTS007 and i have to split numbers from letters so in result i should get an array like {"46", "MTS", "007"}

String s = "46MTS007";
String[] spl = s.split("\\d+|\\D+");

But spl remains empty, what's wrong with the regex? I've tested in regex101 and it's working like expected (with global flag)

If you want to use split you can use this lookaround based regex:

(?<=\d)(?=\D)|(?<=\D)(?=\d)

RegEx Demo

Which means split the places where next position is digit and previous is non-digit OR when position is non-digit and previous position is a digit.

In Java:

String s = "46MTS007";
String[] spl = s.split("(?<=\\d)(?=\\D)|(?<=\\D)(?=\\d)");

Regex you're using will not split the string. Split() splits the string with regex you provide but regex used here matches with whole string not the delimiter. You can use Pattern Matcher to find different groups in a string.

public static void main(String[] args) {
    String line = "46MTS007";
    String regex = "\\D+|\\d+";
    Pattern pattern = Pattern.compile(regex);
    Matcher m  = pattern.matcher(line);    
    while(m.find())
        System.out.println(m.group());
}

Output:

46
MTS
007

Note: Don't forget to user m.find() after capturing each group otherwise it'll not move to next one.

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