Removing the comments from a string

后端 未结 2 1204
青春惊慌失措
青春惊慌失措 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");
    
    0 讨论(0)
  • 2021-01-21 03:26
    replaceAll("((/\\*)[^/]+(\\*/))|(//.*)", "")
    

    This will remove single line, multi-line or doc comments.

    The JavaScript compatible regex is ((/\*)[^/]+(\*/))|(//.*), which you can try with regexpal.com.

    0 讨论(0)
提交回复
热议问题