Separating Letters and Numbers in a String
In Java, you can encounter the need to split a string that contains both letters and digits into alternating segments. For instance, given the string "123abc345def," you might aim for the following result:
x[0] = "123" x[1] = "abc" x[2] = "345" x[3] = "def"
To achieve this precise separation, you can employ the following regular expression:
str.split("(?<=\D)(?=\d)|(?<=\d)(?=\D)");
This pattern splits the string at specific points based on two conditions:
By splitting the string at these positions, you can isolate the alternating segments of letters and numbers.
Explanation of the Regexp:
Example Usage:
String str = "123abc345def";
String[] x = str.split("(?<=\D)(?=\d)|(?<=\d)(?=\D)");
After executing the above code, the x array will contain the alternating segments as desired:
x[0] = "123" x[1] = "abc" x[2] = "345" x[3] = "def"
This technique enables you to efficiently separate letters and digits in a string, allowing you to process them according to their types.
The above is the detailed content of How to Split a String with Letters and Numbers into Alternating Segments in Java?. For more information, please follow other related articles on the PHP Chinese website!