如何使用正则表达式抑制单行和多行注释



我需要找到字符串中的所有多行注释,并用空格(如果注释在一行中)或n(如果注释在多行上)替换它们。例如:

int/* one line comment */a;

应改为:

int a;

而这个:

int/* 
more
than one
line comment*/a;

应改为:

int
a;

有一个包含所有文本的字符串,我使用了以下命令:

file = file.replaceAll("(/\*([^*]|(\*+[^*/]))*\*+/)"," ");

其中文件是字符串。

问题是它找到了所有多行注释,我想将其分为 2 个案例。我该怎么做?

可以使用Matcher.appendReplacementMatcher.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 */"

替换为

"         "

最新更新