Java 匹配注释的正则表达式

参考http://iregex.org/blog/uncomment-program-with-regex.html

通用注释有两种:

  1. //

  2. /*......*/

通常情况下,行级注释可以这样匹配

1
\/\/[^\n]*

块级别这样

1
\/\*([^\*^\/]*|[\*^\/*]*|[^\**\/]*)*\*\/

或者还可以这样

1
\/\*(\s|.)*?\*\/

不过在特殊情况中,行级别会跟协议前缀冲突,所以还需要特殊处理

1
(?<!http:)\/\/.*

甚至于不限定于http协议

1
(?<!:)\/\/.*

最终处理注释为:

1
2
3
4
5
6
7
/*** 处理注释 groovy代码  
* @param text
* @return
***/
def removeComment(text) {
return text.replaceAll("(?<!:)\\/\\/.*|\\/\\*(\\s|.)*?\\*\\/", "")
}
作者

xeonds

发布于

2022-11-22

更新于

2024-05-13

许可协议

评论