4

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)

2 Answers 2

1

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)");
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.