4 回答
TA贡献1712条经验 获得超3个赞
要使其工作,您需要“跳过”字符串文字。您可以通过匹配字符串文字、捕获它们以便保留它们来做到这一点。
以下正则表达式将执行此操作,用作$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条经验 获得超15个赞
我推荐一个两步过程;一个基于行尾 (//),另一个不基于行尾 (/* */)。
我喜欢帕维尔的想法;但是,我看不到它如何检查以确保星号是斜线后的下一个字符,反之亦然。
我喜欢安德烈亚斯的想法;但是,我无法让它处理多行注释。
https://docs.oracle.com/javase/specs/jls/se12/html/jls-3.html#jls-CommentTail
TA贡献1872条经验 获得超3个赞
正如其他人所说,正则表达式在这里不是一个好的选择。您可以使用简单的DFA来完成此任务。
这是一个示例,它将为您提供多行注释 ( /* */) 的间隔。
您可以对单行注释 ( // -- \n) 执行相同的方法。
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条经验 获得超8个赞
也许,最好从多个简单的表达式开始,逐步进行,例如:
.*(\s*\/\*.*|\s*\/\/.*)
最初删除内联评论。
演示
测试
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);
添加回答
举报