簡體   English   中英

Java使用正則表達式檢測字符串中的第一級“ if”條件

[英]Java detect first level “if” conditions in a string with regex

我正在嘗試檢測一段文本中的第一級“如果”條件。 示例文字:

if (a == 5) {
    method1();
    method2()
}
if (a == 6) {
    method1();
    if (a < 2) {
        method3();
    }
}
if (a >= 8 && a <= 13) {
    method5(a);
    int[] b = new int[a];
    for(int i = 0; i < a; i++) {
        if (i == 0) {
            b[i] = i * 4;
            continue;
        }
        b[i] = i * 2;
    }
    method4(b);
}
if (a > 16) {
    method6();
}

這是我到目前為止所得到的:

public class HelloWorld
{
  public static void main(String[] args)
  {
    String text = "if (a == 5) {\n\tmethod1();\n\tmethod2()\n}\nif (a == 6) {\n\tmethod1();\n\tif (a < 2) {\n\t\tmethod3();\n\t}\n}\nif (a >= 8 && a <= 13) {\n\tmethod5(a);\n\tint[] b = new int[a];\n\tfor(int i = 0; i < a; i++) {\n\t\tif (i == 0) {\n\t\t\tb[i] = i * 4;\n\t\t\tcontinue;\n\t\t}\n\t\tb[i] = i * 2;\n\t}\n\tmethod4(b);\n}\nif (a > 16) {\n\tmethod6();\n}";
    for(String line : text.split("if (.*) \\{")) {
      System.out.println("Line: " + line);
    }
  }
}

輸出:

Line: 
Line: 
    method1();
    method2()
}

Line: 
    method1();

Line: 
        method3();
    }
}

Line: 
    method5(a);
    int[] b = new int[a];
    for(int i = 0; i < a; i++) {

Line: 
            b[i] = i * 4;
            continue;
        }
        b[i] = i * 2;
    }
    method4(b);
}

Line: 
    method6();
}

它還會打印嵌套的ifs。 我只想要第一級的。 並且如果在打印行時if將會消失。 我也要顯示。

我基本上想將所有第一級ifs分組為一個字符串。 有人可以幫我弄這個嗎?

由於必須處理嵌套的括號,因此將難以維護適當的正則表達式,如SO中所述。 如何在Java中將括號內的字符串(嵌套)匹配?

我的解決方案是:

  1. 做一些預處理來替換嵌套的括號
  2. 使用正則表達式捕獲if內容
  3. 最后,進行后處理以移交真正的括號
package demo;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Parser {

    private static final char OPENED_BRACKET = '{';
    private static final char CLOSED_BRACKET = '}';
    private static final String OPENED_BRACKET_REPLACOR = "##OPENED_BRACKET_REPLACOR##";
    private static final String CLOSED_BRACKET_REPLACOR = "##CLOSED_BRACKET_REPLACOR##";

    private static final String REGEX    = "\\{((.|\\n|\r|\t)*?)\\}";
    private static final Pattern PATTERN = Pattern.compile(REGEX);

    public String preprocessing(String origin) {
        StringBuilder replaced = new StringBuilder();
        int opened = 0;
        for(int index = 0 ; index < origin.length() ; index++) {
            char current_char = origin.charAt(index);
            String processed  = Character.toString(current_char);

            if(current_char == OPENED_BRACKET) {
                if(opened++ > 0) {
                    processed = OPENED_BRACKET_REPLACOR; 
                }
            }

            else if(current_char == CLOSED_BRACKET) {
                if(--opened > 0) {
                    processed = CLOSED_BRACKET_REPLACOR; 
                }
            }

            replaced.append(processed);
        }
        return replaced.toString();
    }

    public List<String> extract(String source) {
        final Matcher matcher = PATTERN.matcher(source);
        List<String> list = new ArrayList<>();
        while(matcher.find()) {
            list.add(matcher.group(1));
        }
        return list;
    }

    public List<String> postprocessing(List<String> source) {
        List<String> result = new ArrayList<>();
        for(String src: source) {
            result.add(src.replaceAll(OPENED_BRACKET_REPLACOR, Character.toString(OPENED_BRACKET))
                          .replaceAll(CLOSED_BRACKET_REPLACOR, Character.toString(CLOSED_BRACKET)));
        }
        return result;
    }

    public static void main(String[] args) {
        Parser parser = new Parser();
        String code = "if (a == 6) { method1(); if (a < 2) { method3(); } }if (a == 5) { method1();\n\r" +
                      " method2() }";
        String preprocessed = parser.preprocessing(code);
        List<String> extracted = parser.extract(preprocessed);
        List<String> postprocessed = parser.postprocessing(extracted);
        for(String ifContent: postprocessed) {
            System.out.println("Line: " + ifContent);
        }
    }
}

會輸出:

行:method1(); 如果(a <2){method3(); }
行:method1();

method2()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM