title: Java - regular expression finding comments in code
body: <p>A little <strong>fun</strong> with Java this time. I want to write a program that reads a code from standard input (line by line, for example), like:</p>
  
  <pre><code>// some comment
  class Main {
      /* blah */
      // /* foo
      foo();
      // foo */
      foo2();
      /* // foo2 */
  }
  </code></pre>
  
  <p>finds all comments in it and removes them. I'm trying to use regular expressions, and for now I've done something like this:</p>
  
  <pre><code>private static String ParseCode(String pCode)
  {
      String MyCommentsRegex = "(?://.*)|(/\\*(?:.|[\\n\\r])*?\\*/)";
      return pCode.replaceAll(MyCommentsRegex, " ");
  }
  </code></pre>
  
  <p>but it seems not to work for all the cases, e.g.:</p>
  
  <pre><code>System.out.print("We can use /* comments */ inside a string of course, but it shouldn't start a comment");
  </code></pre>
  
  <p>Any advice or ideas different from regex?
  Thanks in advance.</p>