Java - regular expression finding comments in code

后端 未结 5 1119
感动是毒
感动是毒 2020-11-27 18:45

A little fun with Java this time. I want to write a program that reads a code from standard input (line by line, for example), like:

// some         


        
5条回答
  •  孤城傲影
    2020-11-27 19:09

    I ended up with this solution.

    public class CommentsFun {
        static List commentMatches = new ArrayList();
    
        public static void main(String[] args) {
            Pattern commentsPattern = Pattern.compile("(//.*?$)|(/\\*.*?\\*/)", Pattern.MULTILINE | Pattern.DOTALL);
            Pattern stringsPattern = Pattern.compile("(\".*?(? commentsToRemove = new ArrayList();
    
            Matcher stringsMatcher = stringsPattern.matcher(text);
            while (stringsMatcher.find()) {
                for (Match comment : commentMatches) {
                    if (comment.start > stringsMatcher.start() && comment.start < stringsMatcher.end())
                        commentsToRemove.add(comment);
                }
            }
            for (Match comment : commentsToRemove)
                commentMatches.remove(comment);
    
            for (Match comment : commentMatches)
                text = text.replace(comment.text, " ");
    
            System.out.println(text);
        }
    
        //Single-line
    
        // "String? Nope"
    
        /*
        * "This  is not String either"
        */
    
        //Complex */
        ///*More complex*/
    
        /*Single line, but */
    
        String moreFun = " /* comment? doubt that */";
    
        String evenMoreFun = " // comment? doubt that ";
    
        static class Match {
            int start;
            String text;
        }
    }
    

提交回复
热议问题