正则匹配类 C 语言的块注释,包括换行

匹配 C、C++、C# 块注释(多行注释)的正则表达式:

/\*[\s\S\r\n]*?\*/

如果加上行注释,就是

//.*$|/\*[\s\S\r\n]*?\*/

效果:

正则匹配 C、C++、C# 块注释(多行注释)效果

简洁优雅。

注: 其中的正斜杠请根据需要自行转义。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用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 */"` 中的 `/*` 和 `*/` 不应该被视为注释。如果需要排除这种情况,可以使用一些复杂的正则表达式,或者在代码中添加一些特殊处理的逻辑。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值