【问题标题】:Split the string based on different criteria [Optimization Required]根据不同的标准拆分字符串[需要优化]
【发布时间】:2019-01-22 05:10:18
【问题描述】:

我有一个输入字符串,如果该字符串包含 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);
        }
    }
}

【问题讨论】:

  • 碰巧你正在实现一个文本解析器?

标签: java java-8


【解决方案1】:

如果您使用正则表达式,您的代码看起来会更简单(也更易读):

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

这使用lookahead 来匹配elseifelse 后跟的空格,替换为\n,并使用lookbehind 匹配then 之后的空格并将其替换为\n 后跟4 个空格。

然后输出是:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-25
    • 1970-01-01
    • 2011-09-20
    • 2016-11-01
    • 2018-05-12
    相关资源
    最近更新 更多