Removing the comments from a string

后端 未结 2 1223
青春惊慌失措
青春惊慌失措 2021-01-21 02:45

I\'d like to do a function which gets a string and in case it has inline comments it removes it.

public class sample {

    public static void main(String[] arg         


        
2条回答
  •  轮回少年
    2021-01-21 03:15

    Try

    replaceAll("(?s)/\\*.*?\\*/", "")
    

    Example:

    String code = "/**THIS IS SAMPLE CODE */ public class TestFormatter{public static void main(String[] args){int i =2; String s= \"name\";\\\\u give give change the values System.out.println(\"Hello World\");//sample}}";
    System.out.println(code.replaceAll("(?s)/\\*.*?\\*/", ""));
    

    Output:

    public class TestFormatter{public static void main(String[] args){int i =2; String s= "name";\\u give give change the values System.out.println("Hello World");//sample}}
    

    PS.

    if you also want to remove last comments //sample}}

    Then use split()

    System.out.println(code.replaceAll("(?s)/\\*.*?\\*/", "").split("//")[0]);
    // keep in Mind it will also Remove  }} from //sample}} 
    

    Output:

     public class TestFormatter{public static void main(String[] args){int i =2; String s= "name";\u give give change the values System.out.println("Hello World");
    

提交回复
热议问题