How to split a string, but also keep the delimiters?

前端 未结 23 2317
我在风中等你
我在风中等你 2020-11-21 06:32

I have a multiline string which is delimited by a set of different delimiters:

(Text1)(DelimiterA)(Text2)(DelimiterC)(Text3)(DelimiterB)(Text4)
23条回答
  •  执念已碎
    2020-11-21 06:52

        String expression = "((A+B)*C-D)*E";
        expression = expression.replaceAll("\\+", "~+~");
        expression = expression.replaceAll("\\*", "~*~");
        expression = expression.replaceAll("-", "~-~");
        expression = expression.replaceAll("/+", "~/~");
        expression = expression.replaceAll("\\(", "~(~"); //also you can use [(] instead of \\(
        expression = expression.replaceAll("\\)", "~)~"); //also you can use [)] instead of \\)
        expression = expression.replaceAll("~~", "~");
        if(expression.startsWith("~")) {
            expression = expression.substring(1);
        }
    
        String[] expressionArray = expression.split("~");
        System.out.println(Arrays.toString(expressionArray));
    

提交回复
热议问题