Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 658
PYPL Avatar asked Jun 28 '26 02:06

PYPL


1 Answers

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)");
like image 79
anubhava Avatar answered Jun 29 '26 14:06

anubhava