Python2 - 163 134 bytes
import re
def f(s):
for x in re.findall(r'("[^\n]*"(?!\\))|(//[^\n]*$|/(?!\\)\*[\s\S]*?\*(?!\\)/)',s,8):s=s.replace(x[1],'')
print s
Example:
Python 2.7.9 (default, Dec 11 2014, 04:42:00)
[GCC 4.9.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import re
>>> def f(s):
... for x in re.findall(r'("[^\n]*"(?!\\))|(//[^\n]*$|/(?!\\)\*[\s\S]*?\*(?!\\)/)',s,8):s=s.replace(x[1],'')
... print s
...
>>> code = r'''#include <stdio.h>
...
... int main(int argc, char** argv)
... {
... // this comment will be removed
... if (argc > 1) {
... printf("Too many arguments.\n"); // this too will be removed
... return 1;
... }
... printf("Please vist http://this.will.not.be.removed.com\n");
... printf("/* This will stay */\n");
... printf("\"/* This will stay too */\"\n");
... printf("//and so will this\\");
... // but not this
... printf("just \"ano//ther\" test.");
... return 0;
... }
... /*
... this shall disappear
... */
... #include <string>
... int main(int argc, char** argv)
... {
... string foo = ""/*remove that!**/;
... // Remove /* this
... int butNotThis = 42;
... // But do */ remove this
... int bar = 4 /*remove this*/* 3; // but don't remove that 3. */
... return 0;//just a comment
... }/*end of the file has been reached.*/'''
>>> f(code)
#include <stdio.h>
int main(int argc, char** argv)
{
if (argc > 1) {
printf("Too many arguments.\n");
return 1;
}
printf("Please vist http://this.will.not.be.removed.com\n");
printf("/* This will stay */\n");
printf("\"/* This will stay too */\"\n");
printf("//and so will this\\");
printf("just \"ano//ther\" test.");
return 0;
}
#include <string>
int main(int argc, char** argv)
{
string foo = "";
int butNotThis = 42;
int bar = 4 * 3;
return 0;
}