I'm trying to detect first level "if" conditions in a piece of text. Example text:
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();
}
This is what I got so far:
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);
}
}
}
Output:
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();
}
It also prints nested ifs. I only want the first level ones. And the if will disappear when printing the line. I want the if to show too.
I basically want to group all first level ifs into one string. Can some one help me with this?