A string is comprised of the following:
- An optional sequence of ASCII digits.
- A sequence of ASCII lowercase letters.
I'm trying to do the split in one single regex that I could use like this:
String string = "123abc"; var array = string.split(...); System.out.println(java.util.Arrays.toString(array)); // prints [123, abc] The closest regex I've come to is the following:
(?<=\d+) Example:
String string = "123abc"; var array = string.split("(?<=\\d+)"); System.out.println(java.util.Arrays.toString(array)); // prints [1, 2, 3, abc] Technically, I could do this without any regex, but here, it's important to be done with regex.
A solution to prove I can do it normally:
String string = "123abc"; int i = 0; for(; i < string.length() && Character.isDigit(string.charAt(i)); i++) ; String[] array = { string.substring(0, i), string.substring(i) }; System.out.println(java.util.Arrays.toString(array)); // prints [123, abc] Another way of doing it would be:
String string = "123abc"; String[] array = { string.replaceAll("\\D", ""), string.replaceAll("\\d", "") }; System.out.println(java.util.Arrays.toString(array)); // prints [123, abc] Matching examples:
In: Out: 123abc [ "123", "abc" ] 0a [ "0", "a" ] a [ "", "a" ]
"abc".split(...)which returns[ "abc" ], not[ "", "abc" ]."(\\d*)(\\D+)"or"(\\d*)(\\D*)"and get Group 1 and 2.split()? If I wanted to use regex for this, I'd use matching groups instead:string.matches("(\d+)([a-z]+)")split. As shown in the solutions that work without regex or without split, I have no issue to make it work without split. I'm only interested in asplitsolution.When there is a positive-width match at the beginning of the input sequence then an empty leading substring is included at the beginning of the resulting array. A zero-width match at the beginning however never produces such empty leading substring..