How to split a string between letters and digits (or between digits and letters)?
You could try to split on (?<=\D)(?=\d)|(?<=\d)(?=\D)
, like:
str.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)");
It matches positions between a number and not-a-number (in any order).
(?<=\D)(?=\d)
- matches a position between a non-digit (\D
) and a digit (\d
)(?<=\d)(?=\D)
- matches a position between a digit and a non-digit.
How about:
private List<String> Parse(String str) {
List<String> output = new ArrayList<String>();
Matcher match = Pattern.compile("[0-9]+|[a-z]+|[A-Z]+").matcher(str);
while (match.find()) {
output.add(match.group());
}
return output;
}
You can try this:
Pattern p = Pattern.compile("[a-z]+|\\d+");
Matcher m = p.matcher("123abc345def");
ArrayList<String> allMatches = new ArrayList<>();
while (m.find()) {
allMatches.add(m.group());
}
The result (allMatches) will be:
["123", "abc", "345", "def"]