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

标签 java regex string

我需要找到字符串中的所有多行注释并将它们替换为空格(如果注释在一行中)或 \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/

相关文章:

c++ - 你如何在 C++ 中拆分数组?

php - 从字符串的开头删除一个字符串

Java 分析器 : JProbe Replacement for Mac?

java - stage.setIconify(true) 不适用于未装饰的舞台

正则表达式仅在没有前面的情况下才替换

正则表达式匹配数字两次或四次

python - 使用正则表达式匹配文字记录中的姓名、对话和 Action

java - 如何在java中保存非常大的二进制代码

java - 在java中对2d字符串数组进行排序 - 对数组中的索引元素进行排序

regex - VIM - 正则表达式 - 多行搜索查询字段值的变化