注释结束或结束语句后拆分字符串

时间:2016-06-22 05:10:55

标签: java regex string

我有一个代码:

String code = "class foo { // class named foo\n
                   public void fo() { // a method no parameter named fo\n
                       int[]a = {\n
                           1,2,3,4\n
                       };\n
                       for(int b : a){ // loop b as many as a\n
                           if(b%2==0){\n
                               System.out.println(b); // print out b\n
                           }\n
                       }\n
                   }\n
               }";

因此,我希望在每个结束注释或结束语句后将代码拆分为单独的字符串。这是一个例子:

1. class foo { // class named foo
2. public void fo() { // a method no parameter named fo
3. int[]a = {
       1,2,3,4
   };
4. for(int b : a){ // loop b as many as a
5. if(b%2==0){
       System.out.println(b); // print out b

我正在尝试制作代码:

for(String get : code.split("(?<=;)|(?<=;(//.+))"))

但是,它不起作用。

2 个答案:

答案 0 :(得分:2)

这打印出你想要达到的目标......

public static void main(String[] args) {
    try {
        String code = "class foo { // class named foo\n" + 
                      "public void fo() { // a method no parameter named fo\n" + 
                      "int[]a = {\n" + 
                      " 1,2,3,4\n" + "};\n" + 
                      "for(int b : a){ // loop b as many as a\n" + 
                      "if(b%2==0){\n" + 
                      " System.out.println(b); // print out b\n" + 
                      "}\n" + "}\n" + "}\n" + "}";

        String requiredData = "";
        short count = 1;
        for (String data : code.split("\n")) {
            if (data.contains("//") || data.contains(";")) {
                requiredData = requiredData + data;
                System.out.println(count + ". " + requiredData);
                requiredData = "";
                count++;
            } else {
                if (requiredData.isEmpty())
                    requiredData = data + "\n";
                else
                    requiredData = requiredData + data + "\n";
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

这是上述代码的输出......

1. class foo { // class named foo
2. public void fo() { // a method no parameter named fo
3. int[]a = {
    1,2,3,4
};
4. for(int b : a){ // loop b as many as a
5. if(b%2==0){
    System.out.println(b); // print out b

答案 1 :(得分:1)

你不能用换行符分割。就像这样:

for(String x: code.split("(\r?\n)")){
        System.out.println(x);
    }