private static String filterString(String code) {
String partialFiltered = code.replaceAll("/\\*.*\\*/", "");
String fullFiltered = partialFiltered.replaceAll("//.*(?=\\n)", "");
return fullFiltered;
}
I tried above code to remove all comments in a string but it isn't working - please help.
Maybe this can help someone:
Use this regexp to test
((['"])(?:(?!\2|\\).|\\.)*\2)|\/\/[^\n]*|\/\*(?:[^*]|\*(?!\/))*\*\/
hereWorks with both
// single
and multi-line/* comments */
.Input :
Output :
How about....
You need to use
(?s)
at the start of yourpartialFiltered
regex to allow for comments spanning multiple lines (e.g. see Pattern.DOTALL with String.replaceAll).But then the
.*
in the middle of/\\*.*\\*/
uses a greedy match so I'd expect it to replace the whole lot between two separate comment blocks. E.g., given the following:Haven't tested this so am risking egg on my face but would expect it to remove the whole lot including the code in the middle rather than just the two comments. One way to prevent would be to use
.*?
to make the inner matching non-greedy, i.e. to match as little as possible:Since the
fullFiltered
regex doesn't begin with(?s)
, it should work without the(?=\\n)
(since thereplaceAll
regex doesn't span multiple lines by default) - so you should be able to change it to:There are also possible issues with looking for the characters denoting a comment, e.g. if they appear within a string or regular expression pattern but I'm assuming these aren't important for your application - if they are it's probably the end of the road for using simple regular expressions and you may need a parser instead...
Replace below code
partialFiltered.replaceAll("//.*(?=\\n)", "");
With,
partialFiltered.replaceAll("//.*?\n","\n");