I have a string which contains a contiguous chunk of digits and then a contiguous chunk of characters. I need to split them into two parts (one integer part, and one string).
I tried using String.split("\\D", 1), but it is eating up first character.
I checked all the String API and didn’t find a suitable method.
Is there any method for doing this thing?
Use lookarounds:
str.split("(?<=\\d)(?=\\D)")\dis the character class for digits;\Dis its negation. So this zero-matching assertion matches the position where the preceding character is a digit(?<=\d), and the following character is a non-digit(?=\D).References
Related questions
Alternate solution using limited split
The following also works:
This splits just before we see a non-digit. This is much closer to your original solution, except that since it doesn’t actually match the non-digit character, it doesn’t “eat it up”. Also, it uses
limitof2, which is really what you want here.API links
String.split(String regex, int limit)nis greater than zero then the pattern will be applied at mostn - 1times, the array’s length will be no greater thann, and the array’s last entry will contain all input beyond the last matched delimiter.