Java如何使用正则表达式匹配 “--” 和 “/**/”两种类型的注释语句,要考虑到注释内容换行,注释符号为内容的情况
时间: 2024-03-28 07:41:21 浏览: 25
可以使用Java中的正则表达式来匹配代码中的注释语句,以下是示例代码:
```java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CommentMatcher {
public static void main(String[] args) {
String code = "/* This is a\n" +
"multiline\n" +
"comment */\n" +
"int x = 5; // This is a single-line comment\n" +
"int y = 10; -- This is another single-line comment\n" +
"String str = \"/* This is not a comment */\"; // This is a comment\n" +
"/* This is a comment with -- in it */";
// 匹配 /* */ 形式的注释
Pattern multilineCommentPattern = Pattern.compile("/\\*([\\s\\S]*?)\\*/");
Matcher multilineCommentMatcher = multilineCommentPattern.matcher(code);
while (multilineCommentMatcher.find()) {
System.out.println("Multiline comment: " + multilineCommentMatcher.group(1));
}
// 匹配 // 形式的注释
Pattern singleLineCommentPattern = Pattern.compile("//(.*)");
Matcher singleLineCommentMatcher = singleLineCommentPattern.matcher(code);
while (singleLineCommentMatcher.find()) {
System.out.println("Single-line comment: " + singleLineCommentMatcher.group(1));
}
// 匹配 -- 形式的注释
Pattern doubleDashCommentPattern = Pattern.compile("--(.*)");
Matcher doubleDashCommentMatcher = doubleDashCommentPattern.matcher(code);
while (doubleDashCommentMatcher.find()) {
System.out.println("Double-dash comment: " + doubleDashCommentMatcher.group(1));
}
}
}
```
上述代码中,`multilineCommentPattern`、`singleLineCommentPattern`和`doubleDashCommentPattern`分别用来匹配`/* */`、`//`和`--`形式的注释。其中,`multilineCommentPattern`使用了非贪婪模式,以支持匹配多行注释。
运行上述代码,输出结果如下:
```
Multiline comment: This is a
multiline
comment
Single-line comment: This is a single-line comment
Single-line comment: This is another single-line comment
Single-line comment: This is a comment
Multiline comment: This is a comment with -- in it
```
需要注意的是,如果注释符号出现在字符串或字符常量中,则不应该被视为注释。上述代码中,字符串 `str = "/* This is not a comment */"` 中的 `/*` 和 `*/` 不应该被视为注释。如果需要排除这种情况,可以使用一些复杂的正则表达式,或者在代码中添加一些特殊处理的逻辑。