Microsoft: Remove comments from code


  • 0
    J

    You are given with a input String which is actually a source code converted to to a String
    public String removeComments (String input) {
    ...
    }

    Example: For the below code snippet
    for(int i=0; i< 10 /*Upper Limit */; i++) {
    i++; // comment1
    }

    Input: for(int i=0; i< 10 /*Upper Limit */; i++) {\ni++; // comment1\n}
    Return:for(int i=0; i< 10 ; i++) {\ni++; \n}


  • 0
    A
    public string removeComments(string input) {
            string multiLineCommentPattern = "(/\\*.*?\\*/)";
            string singleLineCommentPattern = "(//.*(\n|\\\\n))";
            Regex regex = new Regex($"{multiLineCommentPattern}|{singleLineCommentPattern}", RegexOptions.IgnoreCase);;
            return regex.Replace(input, "");
    }
    

  • 0
    J

    @amatracaru Do you think this is right solution? Have you considered all possibilities?


  • 0
    A

    @JustVirtually updated my answer, should be more robust now


  • 0
    J

    @amatracaru
    Try for
    System.out.println("// Comment");
    System.out.println("/* Comment*/");


  • 1
    A

    @JustVirtually Ok, got your point.
    In fact, in the context of source code, those are just string values, not comments.
    So changing the patterns in my code to use negative lookbehind in order to ignore the pattern if it starts with ":

    string multiLineCommentPattern = "((?<!\")(/\\*.*?\\*/))";
    string singleLineCommentPattern = "((?<!\")(//.*\n))";
    

    Of course, it's still not good enough as it will still break for something like System.out.println("whatever // Comment");.

    Long story short, would love to see the solution :).


  • 0
    J

    @amatracaru
    Yes, Everything that is a part of source code should not get affected by comment remover.


  • 0
    K
    This post is deleted!

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.