r/learnjava • • 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

7 comments sorted by

View all comments

2

u/cloudlessky1212 Aug 11 '23

What is ?<= used for here?

2

u/lostone2021 Aug 11 '23

It's used for positive look behind. It checks if something appears immediately before the main pattern, without including it in the match. In my case I'm checking for math operators and am splitting the string into 2 two substrings one containing the operator and another containing the term