18

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 comment
class Main {
    /* blah */
    // /* foo
    foo();
    // foo */
    foo2();
    /* // foo2 */
}

finds all comments in it and removes them. I'm trying to use regular expressions, and for now I've done something like this:

private static String ParseCode(String pCode)
{
    String MyCommentsRegex = "(?://.*)|(/\\*(?:.|[\\n\\r])*?\\*/)";
    return pCode.replaceAll(MyCommentsRegex, " ");
}

but it seems not to work for all the cases, e.g.:

System.out.print("We can use /* comments */ inside a string of course, but it shouldn't start a comment");

Any advice or ideas different from regex? Thanks in advance.

5
  • I think your exact example is screwy: the close comment inside the string will close the comment. However, an open comment inside a string that isn't in a comment won't start one.
    – Grandpa
    Nov 1, 2009 at 12:53
  • Yep, my bad. I was trying to give something tricky here and tricked myself.
    – brovar
    Nov 1, 2009 at 12:55
  • I would appreciate if you could consolidate and put it in the answer after you have tried it. i am also looking for a similar solution
    – Ravisha
    Sep 27, 2010 at 4:09
  • @Ravisha, I just saw your comment. I'll look for my code as it was only a one-time task and post it here if I find it.
    – brovar
    Oct 2, 2010 at 7:58
  • @brovor.. nice to see a response... Thanks in advance BTW:)
    – Ravisha
    Oct 4, 2010 at 4:23

5 Answers 5

29

You may have already given up on this by now but I was intrigued by the problem.

I believe this is a partial solution...

Native regex:

//.*|("(?:\\[^"]|\\"|.)*?")|(?s)/\*.*?\*/

In Java:

String clean = original.replaceAll( "//.*|(\"(?:\\\\[^\"]|\\\\\"|.)*?\")|(?s)/\\*.*?\\*/", "$1 " );

This appears to properly handle comments embedded in strings as well as properly escaped quotes inside strings. I threw a few things at it to check but not exhaustively.

There is one compromise in that all "" blocks in the code will end up with space after them. Keeping this simple and solving that problem would be very difficult given the need to cleanly handle:

int/* some comment */foo = 5;

A simple Matcher.find/appendReplacement loop could conditionally check for group(1) before replacing with a space and would only be a handful of lines of code. Still simpler than a full up parser maybe. (I could add the matcher loop too if anyone is interested.)

5
  • Note: by "partial solution" I mean that I haven't come up with a case yet where it fails and that using it strictly in a replaceAll() will add an extra space after "quoted" strings.
    – PSpeed
    Nov 19, 2009 at 7:19
  • Hi, thanks for your answer, I've just found it. I've already solved the problem another way, but I'm going to try it when I get home, as it looks quite interesting.
    – brovar
    Nov 23, 2009 at 10:03
  • 1
    Sorry but this regex ` You may have already given up on this by now but I was intrigued by the problem. I believe this is a partial solution... Native regex: //.*|("(?:\[^"]|\\"|.)*?")|(?s)/*.*?*/` matches String str = "Calling a zip function"; Feb 6, 2017 at 6:22
  • This also seems to match strings outside of comments. May 3, 2020 at 3:21
  • It matches all kinds of strings but will replace them with themselves. That's the trick. So it will match "Calling a zip function", for example, and replace it with itself. It will match /* some comment */ and replace it with nothing. It may be that there are cases where it doesn't replace comments in code but not in strings but no one has presented an example yet.
    – PSpeed
    May 4, 2020 at 6:37
3

The last example is no problem I think:

/* we comment out some code
System.out.print("We can use */ inside a string of course");
we end the comment */

... because the comment actually ends with "We can use */. This code does not compile.

But I have another problematic case:

int/*comment*/foo=3;

Your pattern will transform this into:

intfoo=3;

...what is invalid code. So better replace your comments with " " instead of "".

0
3

I think a 100% correct solution using regular expressions is either inhuman or impossible (taking into account escapes, etc.).

I believe the best option would be using ANTLR- I believe they even provide a Java grammar you can use.

2
  • I'm not making a code parser/translator or anything similar, just trying to create a simple program that would work as described above ;)
    – brovar
    Nov 1, 2009 at 13:13
  • @brovar - he is saying you can't do it without a parser.
    – Stephen C
    Nov 1, 2009 at 13:33
3

I ended up with this solution.

public class CommentsFun {
    static List<Match> commentMatches = new ArrayList<Match>();

    public static void main(String[] args) {
        Pattern commentsPattern = Pattern.compile("(//.*?$)|(/\\*.*?\\*/)", Pattern.MULTILINE | Pattern.DOTALL);
        Pattern stringsPattern = Pattern.compile("(\".*?(?<!\\\\)\")");

        String text = getTextFromFile("src/my/test/CommentsFun.java");

        Matcher commentsMatcher = commentsPattern.matcher(text);
        while (commentsMatcher.find()) {
            Match match = new Match();
            match.start = commentsMatcher.start();
            match.text = commentsMatcher.group();
            commentMatches.add(match);
        }

        List<Match> commentsToRemove = new ArrayList<Match>();

        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;
    }
}
0
0

Another alternative is to use some library supporting AST parsing, for e.g. org.eclipse.jdt.core has all the APIs you need to do this and more. But then that's just one alternative:)

1
  • Not allowed to use it here - it's kind of a bet when one of the rules is using basic packages only ;) But thanks anyways, gotta take a look at it.
    – brovar
    Nov 1, 2009 at 12:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.