アナンド:
私は、Javaのソースコードファイルからのコメント文のすべての種類を削除します。例:
String str1 = "SUM 10" /*This is a Comments */ ;
String str2 = "SUM 10"; //This is a Comments"
String str3 = "http://google.com"; /*This is a Comments*/
String str4 = "('file:///xghsghsh.html/')"; //Comments
String str5 = "{\"temperature\": {\"type\"}}"; //comments
予想される出力:
String str1 = "SUM 10";
String str2 = "SUM 10";
String str3 = "http://google.com";
String str4 = "('file:///xghsghsh.html/')";
String str5 = "{\"temperature\": {\"type\"}}";
私は達成するために、以下の正規表現を使用しています:
System.out.println(str1.replaceAll("[^:]//.*|/\\\\*((?!=*/)(?s:.))+\\\\*/", ""));
これは私にSTR4及びSTR5の間違った結果を与えます。この問題を解決するために私を助けてください。
アンドレアス・ソリューションを使用します:
final String regex = "//.*|/\\*(?s:.*?)\\*/|(\"(?:(?<!\\\\)(?:\\\\\\\\)*\\\\\"|[^\\r\\n\"])*\")";
final String string = " String str1 = \"SUM 10\" /*This is a Comments */ ; \n"
+ " String str2 = \"SUM 10\"; //This is a Comments\" \n"
+ " String str3 = \"http://google.com\"; /*This is a Comments*/\n"
+ " String str4 = \"('file:///xghsghsh.html/')\"; //Comments\n"
+ " String str5 = \"{\"temperature\": {\"type\"}}"; //comments";
final String subst = "$1";
// The substituted value will be contained in the result variable
final String result = string.replaceAll(regex,subst);
System.out.println("Substitution result: " + result);
STR5を除き、その作業。
アンドレアス:
それを動作させるためには、文字列リテラルを「スキップ」する必要があります。あなたは、彼らが保持できるように、それらをキャプチャし、文字列リテラルを照合することによってそれを行うことができます。
次の正規表現は使用して、それを行います$1
置換文字列として:
//.*|/\*(?s:.*?)\*/|("(?:(?<!\\)(?:\\\\)*\\"|[^\r\n"])*")
参照してくださいregex101デモのために。
Javaコードは次のようになります。
str1.replaceAll("//.*|/\\*(?s:.*?)\\*/|(\"(?:(?<!\\\\)(?:\\\\\\\\)*\\\\\"|[^\r\n\"])*\")", "$1")
説明
//.* Match // and rest of line
| or
/\*(?s:.*?)\*/ Match /* and */, with any characters in-between, incl. linebreaks
| or
(" Start capture group and match "
(?: Start repeating group:
(?<!\\)(?:\\\\)*\\" Match escaped " optionally prefixed by escaped \'s
| or
[^\r\n"] Match any character except " and linebreak
)* End of repeating group
") Match terminating ", and end of capture group
$1 Keep captured string literal