4 回答

TA貢獻1712條經(jīng)驗 獲得超3個贊
要使其工作,您需要“跳過”字符串文字。您可以通過匹配字符串文字、捕獲它們以便保留它們來做到這一點。
以下正則表達式將執(zhí)行此操作,用作$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

TA貢獻1839條經(jīng)驗 獲得超15個贊
我推薦一個兩步過程;一個基于行尾 (//),另一個不基于行尾 (/* */)。
我喜歡帕維爾的想法;但是,我看不到它如何檢查以確保星號是斜線后的下一個字符,反之亦然。
我喜歡安德烈亞斯的想法;但是,我無法讓它處理多行注釋。
https://docs.oracle.com/javase/specs/jls/se12/html/jls-3.html#jls-CommentTail

TA貢獻1872條經(jīng)驗 獲得超4個贊
正如其他人所說,正則表達式在這里不是一個好的選擇。您可以使用簡單的DFA來完成此任務。
這是一個示例,它將為您提供多行注釋 ( /* */) 的間隔。
您可以對單行注釋 ( // -- \n) 執(zhí)行相同的方法。
String input = ...; //here's your input String
//0 - source code,
//1 - multiple lines comment (start) (/ char)
//2 - multiple lines comment (start) (* char)
//3 - multiple lines comment (finish) (* char)
//4 - multiple lines comment (finish) (/ char)
byte state = 0;
int startPos = -1;
int endPos = -1;
for (int i = 0; i < input.length(); i++) {
switch (state) {
case 0:
if (input.charAt(i) == '/') {
state = 1;
startPos = i;
}
break;
case 1:
if (input.charAt(i) == '*') {
state = 2;
}
break;
case 2:
if (input.charAt(i) == '*') {
state = 3;
}
break;
case 3:
if (input.charAt(i) == '/') {
state = 0;
endPos = i+1;
//here you have the comment between startPos and endPos indices,
//you can do whatever you want with it
}
break;
default:
break;
}
}

TA貢獻2021條經(jīng)驗 獲得超8個贊
也許,最好從多個簡單的表達式開始,逐步進行,例如:
.*(\s*\/\*.*|\s*\/\/.*)
最初刪除內聯(lián)評論。
演示
測試
import java.util.regex.Matcher;
import java.util.regex.Pattern;
final String regex = "(.*)(\\s*\\/\\*.*|\\s*\\/\\/.*)";
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";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);
// The substituted value will be contained in the result variable
final String result = matcher.replaceAll(subst);
System.out.println("Substitution result: " + result);
添加回答
舉報