Java 根据不同标准拆分字符串[需要优化]

Java 根据不同标准拆分字符串[需要优化],java,java-8,Java,Java 8,我有一个输入字符串,如果该字符串包含elseif,那么我需要将该字符串拆分为多行,如预期输出所示 if ((tag eq 200)) then set weight 200 elseif ((tag eq 300)) then set weight 300 elseif ((tag eq 400)) then set weight 400 elseif ((tag eq 250)) then set weight 0 else pass endif 我已经实现了

我有一个输入字符串,如果该字符串包含elseif,那么我需要将该字符串拆分为多行,如预期输出所示

if ((tag eq 200)) then
    set weight 200
elseif ((tag eq 300)) then
    set weight 300
elseif ((tag eq 400)) then
    set weight 400
elseif ((tag eq 250)) then
    set weight 0
else pass endif
我已经实现了下面的代码来拆分,正如上面所示。它正在产生预期的结果。但是下面的代码不是优化的。有人能为下面的代码段提出任何优化建议吗

public class Test {

    public static void main(String[] args) {
        String str = "if ((tag eq 200)) then set weight 200  elseif ((tag eq 300)) then set weight 300  elseif ((tag eq 400)) then set weight 400 elseif ((tag eq 250)) then set weight 0 else pass endif";
        System.out.println(str);

        if(str.contains("elseif")) {
            int lastIndex = str.lastIndexOf("then");
            String subString = str.substring(0, lastIndex + 4);
            splitTextByThen(subString);
            String subString1 = str.substring(lastIndex+4 , str.length());
            splitTextByElseIfOrElse(subString1);
        }
    }

    public static void splitTextByThen(String input) {
        String[] arr = input.split("then");
        for (int i = 0; i < arr.length; i++) {
            splitTextByElseIfOrElse(arr[i] + "then");
        }
    }

    public static void splitTextByElseIfOrElse(String input) {
        ArrayList<String> al = new ArrayList<>();
        if(input.contains("elseif")) {
            String[] arr = input.split("elseif");
            al.add(arr[0]);
            al.add("elseif " +arr[1]);
        }else if (input.contains("else")) {
            String[] arr = input.split("else");
            al.add(arr[0]);
            al.add("else " +arr[1]);
        }
        else {
            al.add(input);
        }

        for (String string : al) {
            System.out.println(string);
        }
    }
}
公共类测试{
公共静态void main(字符串[]args){
String str=“如果((标记eq 200)),则设置权重200 elseif((标记eq 300)),然后设置权重300 elseif((标记eq 400)),然后设置权重400 elseif((标记eq 250)),然后设置权重0 else pass endif”;
系统输出打印项次(str);
如果(str.contains(“elseif”)){
int lastIndex=str.lastIndexOf(“then”);
String subString=str.subString(0,lastIndex+4);
splitTextByThen(子字符串);
String subString1=str.substring(lastIndex+4,str.length());
splitTextByElseIfOrElse(子字符串1);
}
}
公共静态void splittextbyten(字符串输入){
字符串[]arr=input.split(“then”);
对于(int i=0;i
如果使用正则表达式,代码看起来会更简单(可读性也更高):

String result = str.replaceAll(" (?=elseif|else)", "\n")
                   .replaceAll("(?<=then) ", "\n    ");

碰巧,您正在实现一个文本解析器?
if ((tag eq 200)) then
    set weight 200 
elseif ((tag eq 300)) then
    set weight 300 
elseif ((tag eq 400)) then
    set weight 400
elseif ((tag eq 250)) then
    set weight 0
else pass endif