Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java – Split string into a list of numers or characters

If I have say "ic182nob2"
I would like to split that into an array list string of

["i","c", "182", "n", "o", "b", "2"]

I tried the split string with regex, but i ended up getting "ic", "182", "nob", "2" which is not what i want

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

We can try splitting on the regex alternation (?<=\\D)|(?=\\D):

String input = "ic182nob2";
String[] parts = input.split("(?<=\\D)|(?=\\D)");
System.out.println(Arrays.toString(parts));  // [i, c, 182, n, o, b, 2]

The above logic makes a split when either the preceding or following character is not a digit:

(?<=\\D)  what precedes is not a digit
|         OR
(?=\\D)   what follows is not a digit
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading