Home >Java >javaTutorial >How to Split a String Between Letters and Digits in Java Using Regular Expressions?
Splitting Strings Between Letters and Digits in Java
A common task in programming is to split a string that alternates between letters and numbers. For example, given a string like "123abc345def," one might want to separate it into ["123", "abc", "345", "def"].
To achieve this, one can employ regular expressions to capture the pattern. In Java, the following regular expression can be used:
(?<=\D)(?=\d)|(?<=\d)(?=\D)
Explanation:
Example usage:
String str = "123abc345def";
String[] splitted = str.split("(?<=\D)(?=\d)|(?<=\d)(?=\D)");
for (String part : splitted) {
System.out.println(part);
}
This code will print:
123 abc 345 def
Note that the number of letters and numbers in the string can vary. The regular expression will correctly split the string based on the pattern.
The above is the detailed content of How to Split a String Between Letters and Digits in Java Using Regular Expressions?. For more information, please follow other related articles on the PHP Chinese website!