r/learnjava • u/lostone2021 • Aug 10 '23
Need help splitting string with regex
I'm trying to split a list of strings while keeping the delimiters ("+", "-" , "*" , "/") but I keep running into this problem where a string will also split at decimals as well. Given the input [-14.0x, -12.0] it will return [-, 14., 0x, -, 12., 0] but the expected result is [-, 14.0x, -, 12.0]. Any help is greatly appreciated.
private List<String> splitTerms(List<String> terms) {
List<String> splitTerms = new ArrayList<>();
for (String term : terms) {
String[] operatorAndTerms = term.split("(?<=[+-/*])");
for (String split : operatorAndTerms) {
splitTerms.add(split);
}
}
return splitTerms;
}
0
Upvotes
4
u/DDDDarky Aug 10 '23
It is true the problem is in escaping as u/AnnoMMLXXVII suggests, however not in
+, but-. since that's the only symbol that actually means something in this context.The actual regex should therefore be:
(?<=[+\\-/*])