我需要找到字符串中的所有多行注释并将它们替换为空格(如果注释在一行中)或 \n
(如果注释在多行中) ).
例如:
int/* one line comment */a;
应该改为:
int a;
还有这个:
int/*
more
than one
line comment*/a;
应该改为:
int
a;
我有一个包含所有文本的字符串,我使用了这个命令:
file = file.replaceAll("(/\\*([^*]|(\\*+[^*/]))*\\*+/)"," ");
其中文件是字符串。
问题是它找到了所有的多行评论,我想把它分成两种情况。 我该怎么做?
最佳答案
这可以使用 Matcher.appendReplacement
解决和 Matcher.appendTail
.
String file = "hello /* line 1 \n line 2 \n line 3 */"
+ "there /* line 4 */ world";
StringBuffer sb = new StringBuffer();
Matcher m = Pattern.compile("(?m)/\\*([^*]|(\\*+[^*/]))*\\*+/").matcher(file);
while (m.find()) {
// Find a comment
String toReplace = m.group();
// Figure out what to replace it with
String replacement = toReplace.contains("\n") ? "\n" : "";
// Perform the replacement.
m.appendReplacement(sb, replacement);
}
m.appendTail(sb);
System.out.println(sb);
输出:
hello
there world
注意:如果您想为注释中不的所有文本保留正确的行号/列(如果您想返回引用错误消息等)我会建议做
String replacement = toReplace.replaceAll("\\S", " ");
用空白替换所有非空白。这样 \n
被保留,并且
"/* abc */"
被替换为
" "
关于java - 如何使用正则表达式抑制单行和多行注释?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10580614/